Reputation:
Building a laravel app (Blog/posts). While viewing any particular post(via slug), the url is like this
http://localhost:8000/post/corporate-world-1
So if some puts any random slug,
http://localhost:8000/post/jajdajkjknjfna
it is not showing 404, instead it is like:
ErrorException (E_ERROR)
Trying to get property 'post_image' of non-object (View: C:\xampp\htdocs\blogsnposts\resources\views\post\show.blade.php)
Upvotes: 0
Views: 394
Reputation: 481
This is because you are not handling the 404 in your controller. Without seeing the controller's code, I can only assume that the controller tries to fetch a content from the database with a non-existing slug, returns null but then you still pass the object fetched from the database to the view. You need to test if the objects exists and return a 404 if it doesn't. It would look something like this
function post($slug) {
$post = Post::where('slug', $slug)->first();
// This is probably missing
if (!$post) {
abort(404);
}
return view('show', ['post' => $post]);
}
Upvotes: 2
Reputation: 923
You can add a middleware to the route.
Route::get('post/{post}', PostController@show)->middleware('checkPost');
in kernel.php
'checkPost' => \Illuminate\Routing\Middleware\CheckPostMiddleware::class,
In the middleware you check if the url contains a valid post else
return abort(404);
Upvotes: 0