Pagination hasMany Laravel 5.1

Asked

Viewed 260 times

4

I have the following relationship in my Model Client:

public function Usuario(){ 
    return $this->hasMany('SIST\Models\Admin\Usuario', 'id_cliente');
}

I pass the customer data through my Controller:

$cliente = Cliente::find($id_cliente);
return view('admin/usuario/index',['cliente' => $cliente]);

And I list users in my View:

@foreach($cliente->Usuario as $usuario)

I need to know how to paginate the results.

1 answer

2


Instead of directly calling the relationship, you can use the relaciomanento method to be able to call the paginate.

$cliente = Cliente::findOrFail($id_cliente);

$usuarios = $cliente->usuarios()->paginate(15);

In the view, you will replace $cliente->usuarios for $usuarios in his foreach.

And to display the pagination links, do so on view:

  {{ $usuarios->links() }}

You can also use the method $usuario->render() optionally. These two methods serve the same purpose.

  • 1

    IS links(), render() or tantofaz() ?

  • Really ? It’s in the documentation. https://laravel.com/docs/5.1/pagination#Displaying-Results-in-a-view

  • It is to show the pagination links on view yes. Direct use of render().

  • I’ll see. I don’t know the Paginator. I didn’t mean you’re wrong and I’m right. The links() flame to render. return $this->render($presenter);. It’s just the name of the call... thanks!

  • 1

    @Zoom was worried about being wrong. I do not use the Laravel 5, I use the 4. But as they say that is almost the same thing, I risked to answer :D

  • I started using Lavarel in 4.2. After the 5.0 came out... I already migrated. The hard is paging on mobile device.

  • Okay, thank you very much!

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.