douba3975 2015-01-12 21:11
浏览 66
已采纳

检查是否没有该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?
  • ...
  • 写回答

2条回答 默认 最新

  • dongsui8162 2015-01-12 21:19
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?