1 - Return 404 When Querying Model
When querying the model using "findOrFail($x)" or "firstOrFail()" it can automatically return a not found record.
public function show($id) { $post = Post::findOrFail($id); $firstPost = Post::firstOrFail(); }
2 - Use abort(404)
The second way is to use "abort(404)" from the location of the code you want it to abort. Having this function will give the 404 status code of the page not found.
public function show($id) { // your other code abort(404); }
3 - Using Custom Response
The third way is to return a response with 404 status code.
public function show($id) { // your other code return response(['error' => true, 'error-msg' => 'Not found'], 404); }
4 - Return Custom 404 View
Finally, if you have custom 404 then you can return the views with the 404 status code.
public function show($id) { // your other code if ($errorIsTrue) { return response()->view('errors.404', ['error' => 'Not Found'], 404); } }
Those are the ways to return 404 status code from your Laravel app, if you have other ways do share it in the comments down below.
Leave a reply