when I enter the detail page in Laravel, it gives an error. I don't understand where the error is coming from. My codes are as follows. where is the problem? actually it says it's empty, but it needs to pull data from $blog on controller side.
Controller:
public function show($id)
{
$blog = Blog::where('id',$id)->first();
return view('front.detail',compact('blog'));
}
routes/web.php:
Route::prefix('{lang?}')->middleware('locale')->group(function() {
Route::get('/', [MainController::class, 'index'])->name('home');
Route::get('/about', [MainController::class, 'about'])->name('about');
Route::resource('/blogs', MainController::class)->only([ 'show']);
});
detail.blade.php:
<li>
<h2><a href="">{{$blog->title}}</a></h2>
<p>{!! $blog->text !!}</p>
</li>
CodePudding user response:
If you want to get a model by the main column you use find
not where
and the column:
public function show($id)
{
$blog = Blog::find($id);
return view('front.detail',compact('blog'));
}
Then, find
can return the Model (hence an object
) or null
, so in your case it is not finding the model by ID.
What you should use is findOrFail
so it throws an exception if it did not find the model:
public function show($id)
{
$blog = Blog::findOrFail($id);
return view('front.detail',compact('blog'));
}
Then you can continue debugging why it is not found
CodePudding user response:
Doesn't appear you are passing the blog ID in with your URL:
Route::resource('/blogs', MainController::class)->only([ 'show']);
Try changing your route to this:
Route::resource('/blogs/{id}', MainController::class)->only([ 'show']);
Your URL should be something like (where 5 is the blog ID):
http://yourdomain.com/blogs/5
You could also use binding:
// Route
Route::get('/blogs/{blog}', [MainController::class, 'show']);
public function show(Blog $blog)
{
return view('front.detail', ['blog' => $blog]);
}
More info can be found here: Route model binding
CodePudding user response:
When I use this code, it redirects to 404 page.
public function show($id)
{
$blog = Blog::find($id);
return view('front.detail',compact('blog'));
}
When I use this code, it redirects to 404 page.
public function show($id)
{
$blog = Blog::findOrFail($id);
return view('front.detail',compact('blog'));
}