I have two models. Business and City.
Business:
- id
- title
-some columns--
- city_id
City:
- id
- 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
When I want to get it like $business->city_id
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;