Im trying to make a blog with posts, when the title of the posts are clicked on the single post should be displayed. But when I now click on a title I get a 404 not found error. Im sorry in advance for mistakes made on my part, im new to using laravel.
PostController
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'slug';
}
public function index()
{
$name = 'Mijn posts';
//get data from the te model
$posts = Posts::all();
//dd($posts);
return view('posts.index', compact('name', 'posts'));
}
public function show(Post $slug)
{
return view('posts.post', ['post' => $slug]);
}
}
web.php
Route::get('/posts', [\App\Http\Controllers\PostController::class, 'index'])->middleware('auth');
Route::get('/posts/{slug}', [UserController::class, 'show']);
Post.blade
@extends('layouts.app')
@section('showpost')
<div>
@foreach ($posts as $post)
<h1> {{ $post->title }} </h1>
<p> {{ $post->body }} </p>
@endforeach
</div>
@endsection
What am I missing?
CodePudding user response:
First you need to add a route name:
Route::get('/posts/{slug}', [UserController::class, 'show'])->name('post.show');
Second you need to change <h1> to <a href="{{route('post.show',$post)}}">
CodePudding user response:
Route model binding did't get the slug If you try this way it will be done
PostController
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'slug';
}
public function index()
{
$name = 'Mijn posts';
//get data from the te model
$posts = Posts::all();
//dd($posts);
return view('posts.index', compact('name', 'posts'));
}
public function show($slug)
{
$slug = Post::where('slug', $slug)->first();
return view('posts.post', ['post' => $slug]);
}