Home > Mobile >  Laravel Relationships, don't know how to display
Laravel Relationships, don't know how to display

Time:02-24

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

CodePudding user response:

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'

CodePudding user response:

You have 2 options. First, you can get city details on the controller:

Business::with('city')...;

On the blade

$business->city->name;

Other option fetching it on the blade directly. I don't recommend this because of extra database queries.

$business->city()->name;
  • Related