Laravel Route - Check if ID does not exist and show 404

Viewed 6543

I don't want to show the page if the ID does not exist.

How can I check this in my web.php routes in Laravel?

I currently have the following route:

Route::get('/public/{project_id}', 'ProjectController@public');

How can I do a conditional check to see if project_id exists?

I saw there was an option for Route::bind in the routing docs -- is that a solution? Thanks

Update Note: Slightly different than the Laravel 4 approach as binding seems to have been baked in to the route class.

5 Answers

What you want to use is called Route Model Binding. Laravel does what you want out of the box. If the ID is not in the database, it shows a 404 page. However, you need to change your route:

Assuming your Model is called Project, the route should look like this:

Route::get('/public/{project}', 'ProjectController@public');

And your ProjectController should look like this:

public function public(Project $project) {

This way Laravel automatically resolves the project with the ID you provide and injects it into the $project variable. If no record with the ID exists, laravel redirects to 404

Adding to Patrick Schocke's answer.

If you do not want to use Route Model Binding, you can explicitly check in the controller

public function public($project_id) {
    $projectExists = Project::where('id', $project_id)->exists();

    abort_unless($projectExists, 404, 'Project not found');

   ...
    }
}

Just use laravel's findOrFail() methode. This method will retrieve the first result of the query; however, if no result is found a 404 HTTP response is automatically sent.

public function public ($project_id) {
    $project = Project::findOrFail($project_id);
}

source : https://laravel.com/docs/5.8/eloquent#retrieving-single-models

You can check if project_id does not exist then return 404 error by calling abort() function.

  public function public($project_id) {
        $project_id_exist = Project::where('id', $project_id)->first();
        if(!$project_id_exist){
            return abort(404);
        }
    }

You can achieve this by using laravel route model binding functionality

your route will be

Route::get('/public/{project}', 'ProjectController@public');

your controller will be

public function public(Project $project) {
       // Do your work here using $project model
       //  If a matching model instance is not found in the database, a 404 HTTP response will automatically be generated. 
}
Related