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 users.id... 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();
Thanks.
This is my web.php route:
Route::get('/posts/tags/tag/{tag}', 'TagsController@show');
This is my controller function for that:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Tag; use App\Post;
class TagsController extends Controller {
public function __construct()
{
$this->middleware('auth')->except(['index']);
}
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'
]);
Tag::create([
'name' => request('name')
]);
return redirect('/');
}
public function show(Tag $tag)
{
return view('tags.show', 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="https://neilpatel-qvjnwj7eutn3.netdna-ssl.com/wp-content/uploads/2015/07/seoimage.jpg" height="270px" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">
<a href="/posts/{{ $post->id }}">
{{ $post->title }}
</a>
</h5>
<p class="card-text">
{{ substr(strip_tags($post->body), 0, 50) }}{{ strlen(strip_tags($post->body)) > 50 ? "..." : "" }}
</p>
<p class="card-text"><small class="text-muted">{{ $post->user->name }} on
{{ $post->created_at->toFormattedDateString() }}</small></p>
<hr>
<a href="/posts/{{ $post->id }}" class="btn btn-warning">Go somewhere</a>
</div>
</div>
</div>
@endforeach
This is my queries (images below):
QUERIES IMAGE 1
QUERIES IMAGE 2