Using relationship in custom view

Solved
julien

Dec 1st, 2020 07:35 AM

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 ?

bobbyiliev

Dec 2nd, 2020 04:06 PM

Best Answer

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!

julien

Dec 2nd, 2020 04:39 PM

yes it helps a lot...

i wasn't sure if redefining the relationship was the good way

Thank you.

thinkverse

Dec 7th, 2020 03:21 AM

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').

appspopo5

Jan 18th, 2021 10:02 AM

Thank you so much for this. I was into this issue and tired to tinker around to check if its possible but couldnt get it done. Now that i have seen the way you did it, thanks guys with regards