我刚刚开始学习laravel,我想使用这个框架的优势。我问这个问题是为了学习与 laravel 的正确方法。
它正在从与$id具有相同 ID 的帖子表中打印帖子。
<?php
class PostsController extends BaseController{
public function singlePost($id)
{
$thePost = Posts::find($id);
return View::make('singlePost')->with('thePost', $thePost);
}
}
通常,我会检查是否有一个帖子的 id 等于 $id,如果是,则返回视图等。难道没有更好的方法来使用 laravel,就像您可以使用路由过滤器一样。
不久
- 如何知道是否有带有该ID的帖子?
- 如果没有,如何抛出异常?
- 。
路由
模型绑定可能是一种选择,但更通用的解决方案是findOrFail
findOrFail
将返回模型或抛出一个显示为 404 页面的ModelNotFoundException
。
$thePost = Posts::findOrFail($id);
return View::make('singlePost')->with('thePost', $thePost);
要只检查是否存在,您可以使用find
然后与null
进行比较:
$thePost = Posts::find($id);
if($thePost != null){
// post exists
}
或者更简单,只是一个真实的值:
$thePost = Posts::find($id);
if($thePost){
// post exists
}
请参阅文档中的"路由模型绑定"。
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);
});
您也可以在代码中将find()
替换为findOrFail()
,这将引发未找到具有该 ID 的帖子的异常。