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>
2
Answers
If you want to get a model by the main column you use
find
notwhere
and the column:Then,
find
can return the Model (hence anobject
) ornull
, 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:Then you can continue debugging why it is not found
Doesn’t appear you are passing the blog ID in with your URL:
Try changing your route to this:
Your URL should be something like (where 5 is the blog ID):
You could also use binding:
More info can be found here:
Route model binding