Using relationship in custom view
Hello, I'm a newbie with both Laravel and Voyager.
I have created a custom controller overriding the VoyagerBaseController for my Clients
And a custom view overrinding the read.blade.php view of Clients
Each clients has many Motscles
And each Motscles has many GoogleSERP
How can i display the 10 first GoogleSERP for each of my Clients' Motscles in my Clients read.blade.php view ?
Hi there Julien,
I think that what you need to do in this case is to threat it just as you would without having Voyager.
- Define your relationship in your Laravel models as you would normally without Voyager
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Motscle extends Model
{
/**
* Get the comments for the blog post.
*/
public function googleserps()
{
return $this->hasMany('App\Models\Googleserp');
}
}
- Then Depending on the motorscles that your client is viewing you can get the relationship as follows in your controller:
$googleserps = App\Models\Motscle::find($MotscleID)->googleserps;
Then in your view you could loop through them
@foreach ($googleserps as $googleserp)
//
@endforeach
Hope that this helps!
Also make sure to eager load the relationship to avoid any n(+1) problems. Either by using ::with('googleserps')
or lazily loading using $motscle->load('googleserps')
.