Philosopher
Philosopher

Reputation: 29

Checking if there is not record with that 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,

Upvotes: 0

Views: 57

Answers (2)

lukasgeiter
lukasgeiter

Reputation: 152860

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
}

Upvotes: 1

ceejayoz
ceejayoz

Reputation: 179994

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.

Upvotes: 0

Related Questions