检查是否没有该ID的记录

I've just started to learn about laravel and I want to use this framework with It's advantages. I'm asking this question to learn the right way to this with laravel.

It is printing the post from posts table which has the same id with $id.

<?php
    class PostsController extends BaseController{

        public function singlePost($id)
        {
            $thePost = Posts::find($id);
            return View::make('singlePost')->with('thePost', $thePost);
        }

    }

Normally I do check if there is a post that's id equal to $id and if that is, return view so forth. Isn't there better way to do this with laravel like you can do with route filters.

Shortly,

  • How to know if there is post with that id?
  • How to throw exception if there is not?
  • ...

Route Model Binding might be an option however a more universal solution is findOrFail
findOrFail will either return the model or throw a ModelNotFoundException which will display as a 404 page.

$thePost = Posts::findOrFail($id);
return View::make('singlePost')->with('thePost', $thePost);

To just check for existence you can use find and then compare with null:

$thePost = Posts::find($id);
if($thePost != null){
    // post exists
}

Or simpler, just a truthy value:

$thePost = Posts::find($id);
if($thePost){
    // post exists
}

See "Route Model Binding" in the documentation.

Route::model('post', 'Post', function() {
    // do something if Post is not found
    throw new NotFoundHttpException;
});

Route::get('post/{post}', function(Post $post) {
    return View::make('singlePost')->with('thePost', $post);
});

You could also just replace find() with findOrFail() in your code, which would throw an exception of a post wasn't found with that ID.