I am working with Laravel 5.6 and mysql in my app. and I am new to the Laravel. I have following table as vehicles,
id name number user_id
1 car 123 1
2 van 258 2
3 lorry 125 5
4 car 896 7
and user table like this,
id name email
1 hyu agt@mail.com
2 opv yyuj@mail.com
3 kio juik@mail.com
4 lop kiuf@mail.com
5 hyg htgd@mail.com
Now I need print email using above vehicles table user_id in my blade file, how can I do this? Edit I have following blade file to print vehicles table,
{{$vehicle->name}}
{{$vehicle->number}}
edit my vehiclecontroller,
public function show($id)
{
$vehicles = Vehicle::find($id);
return view('vehicles.show')->withVehicles($vehicles);
}
and show blade file,
<div class="col-md-5" id="vl">
<div><label >Brand:</label>{{$vehicles->name}}</div>
<br>
<div><label >Model:</label>{{$vehicles->number}}</div>
<br>
If you have a relation in place on your Vehicle
model which looks like this:
public function user()
{
return $this->belongsTo(User::class);
}
you can simply access the user
property to get the email
: {{ $vehicle->user->email }}
For improved performance, it makes sense to eager load the users when you fetch the vehicles from the database:
$vehicles = Vehicle::with('user')->get();
First take a look at this to create model for tables and then you can join it for both the tables and get user email too.
$vehicles = Vehicle::select('vehicles.name', 'vehicles.number', 'users.email')
->leftjoin('users', 'users.id', '=', 'vehicles.user_id')->get();
You can also use Laravel relations to achieve this.
$userEmails= DB::table('vehicles')
->join('contacts', 'user.id', '=', 'vehicles.user_id')
->select('users.email')
->get();
Try above code. This is SQL join concept. For your reference https://laravel.com/docs/5.7/queries#joins
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.