mvnobrega's avatar

Relationship paginate does not work

I need to create a dynamic link to take the user to the last page of the laravel page. For example, if there is a pagination, I need to include lastPage () at the end of the url www.site.com/forum/slug?page=2

otherwise it goes to the normal page.

But I need to do this logic on another controller, which in turn is not working. See my relationships and how I'm doing:

Model Grupo:

class Grupo extends Model
{
   	public function relatos()
        {
        return $this->hasMany('App\Relato');
        }
}

Model Relato:

class Relato extends Model
{

    public function comments()
    {
        return $this->hasMany('App\Comment');
    }

}

Getting pagination:

public function grupoPerfil($slug) {


        $grupo = Grupo::where('slug', $slug)->first();

        $comments = $grupo->relatos()->comments()->paginate(10);

            
         return view('grupo', compact(['grupo', 'comments']));
            
        
    }

But when I call the function {{ $comments->lastPage() }}, it always returns 1, and it should return the last page which is 3

Whats wrong ?

0 likes
3 replies
SilenceBringer's avatar
Level 55

Hi @mvnobrega your model Grupo hasMany Relato, so,

$grupo->relatos

is collection. you can't access comments on it. Try to do something like:

public function grupoPerfil($slug)
{
    $grupo = Grupo::where('slug', $slug)->first();

    $comments = Comment::whereHas('relato', function ($query) use ($grupo) {
        return $query->where('grupo_id', $grupo->id);
    })->paginate(10);

            
    return view('grupo', compact(['grupo', 'comments']));        
}

this approach assumes that you have relation in your Comment Model

class Comment extends Model
{

    public function relato()
    {
        return $this->belongsTo('App\Relato');
    }

}
1 like
mvnobrega's avatar

I just discovered another problem. In my case, I am conducting a foreach to capture all reports. And the solution given does not relate the comment to the "relatos"

That is, That is, I am doing this:

@foreach($rels->sortByDesc('updated_at') as $r)

                <card-relatos 
                url="{{localized_route('relatoUser', [$r->grupo->slug, $r->slug])}}"
                getpaginate="{{ $comments->lastPage() }}"
                </card-relatos>

 @endforeach

But getpaginate always returns 2, as it is not related to relato_id. How do I solve this?

Please or to participate in this conversation.