Sultan Kydyrkozha
Sultan Kydyrkozha

Reputation: 15

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

Upvotes: 0

Views: 237

Answers (2)

Starrk
Starrk

Reputation: 44

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'

Upvotes: 1

Bulent
Bulent

Reputation: 3411

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;

Upvotes: 0

Related Questions