laravelrelationshipvoyager

Laravel Relationships, don't know how to display


I have two models. Business and City.

Business:

  1. id
  2. title

-some columns--

  1. city_id

City:

  1. id
  2. name

How to display the city name, when I get business data to view

I was able to display cities using the laravel voyager lessons enter image description here

enter image description here

When I want to get it like $business->city_id enter image description here


Solution

  • If you are using models, you can create a relationship by adding hasOne or hasMany to your model codes. When you call it from your controller, you can call the relationship you wrote in your model with the 'with' query.

    Model

    public function city()
    {
        return $this->hasOne(City::class,'id','cityid');
    }
    

    Controller

    $business=Business::with('city')->first();
    $cityname=$business->city->name;
    

    If you don't use model, you can connect with 'join'