How to eager load the 'user' function from eloquent relationship previously set (User Model) in controller when I have this situation

NOTE: The relationship between Post and Tag model is many to many and the relationship between User and Post model is one to Many. Everything is working well I just have too many Queries from users where when debbug it. I want to use eager loading for the user function, in this situation in my controller function. How do I use it like with('user')->get();


This is my web.php route:

Route::get('/posts/tags/tag/{tag}', 'TagsController@show');

This is my controller function for that:


namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Tag; use App\Post;

class TagsController extends Controller {

public function __construct()




public function index(Tag $tag)


    return view('posts.index', compact('tag'));

public function create()

    return view('tags.create');

public function store(Request $request)


    $this->validate(request(), [

        'name' => 'required|max:255'



        'name' => request('name')            


    return redirect('/');

public function show(Tag $tag)

    return view('', compact('tag'));


This is my show.blade.php:

@foreach ($tag->posts as $post)

              <div class="col-sm-6" >

                  <div class="card" style="margin-bottom:15px;">
                    <img class="card-img-top" src="" height="270px" alt="Card image cap">
                    <div class="card-body">
                      <h5 class="card-title">
                          <a href="/posts/{{ $post->id }}">
                          {{ $post->title }}
                      <p class="card-text">
                       {{ substr(strip_tags($post->body), 0, 50) }}{{ strlen(strip_tags($post->body)) > 50 ? "..." : "" }}
                      <p class="card-text"><small class="text-muted">{{ $post->user->name }} on
                                {{ $post->created_at->toFormattedDateString() }}</small></p>
                      <a href="/posts/{{ $post->id }}" class="btn btn-warning">Go somewhere</a>

This is my queries (images below):



2 answers

  • answered 2018-11-08 01:28 Jesus Erwin Suarez

    In your controller, you can do it like this below and the blade code stays the same.

    $posts = Post::with('user')->get();


    $posts = Post::with(['user'])->get();

    Hope this works for you.

  • answered 2018-11-08 02:20 newUserName02

    You can use a combination of eager loading and lazy eager loading in your controller's show() method. Try something like this:

    public function show(Tag $tag)
        $tag->load(['posts' => function($query) {   // lazy eager load posts
            $query->with('user');                   // eager load users
        return view('', compact('tag'));