php Laravel 5:如何使用 findOrFail() 方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32737812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5 : How to use findOrFail() method?
提问by Dark Cyber
I just follow some tutorial and so far what I do is :
我只是按照一些教程,到目前为止我所做的是:
my App/Exceptions/Handler.php
我的 App/Exceptions/Handler.php
<?php
...
use Illuminate\Database\Eloquent\ModelNotFoundException;
...
public function render($request, Exception $e)
{
if ($e instanceof ModelNotFoundException){
abort(404);
}
return parent::render($request, $e);
}
and my UsersController
looks like this :
我UsersController
看起来像这样:
...
public function edit($id)
{
$data = User::findOrFail($id);
$roles = Role::where('title', '!=', 'Super Admin')->get();
return View('admin.user.edit', compact(['data', 'roles']));
}
...
with the above code if I visit http://my.url/users/10/edit
I get NotFoundHttpException in Application.php line 901:
, yes because there is no id 10 in my record, but with User::find($id);
I get normal view without data, since no id 10 in my record.
使用上面的代码,如果我访问http://my.url/users/10/edit
我得到NotFoundHttpException in Application.php line 901:
,是的,因为我的记录中没有 id 10,但是User::find($id);
我得到没有数据的正常视图,因为我的记录中没有 id 10。
What I want is show default 404 then redirect to somewhere or return something if record not found with User::findOrFail($id);
? How I can do that ?
我想要的是显示默认 404 然后重定向到某个地方或如果没有找到记录则返回某些内容User::findOrFail($id);
?我怎么能做到这一点?
Thanks, any help appreciated.
谢谢,任何帮助表示赞赏。
ps: .env APP_DEBUG = true
ps: .env APP_DEBUG = true
回答by bernie
This does what you asked. No need for exceptions.
这就是你问的。不需要例外。
public function edit($id)
{
$data = User::find($id);
if ($data == null) {
// User not found, show 404 or whatever you want to do
// example:
return View('admin.user.notFound', [], 404);
} else {
$roles = Role::where('title', '!=', 'Super Admin')->get();
return View('admin.user.edit', compact(['data', 'roles']));
}
}
Your exception handler is not necessary as it is. Regarding Illuminate\Database\Eloquent\ModelNotFoundException
:
您的异常处理程序不是必需的。关于Illuminate\Database\Eloquent\ModelNotFoundException
:
If the exception is not caught, a 404 HTTP response is automatically sent back to the user, so it is not necessary to write explicit checks to return 404 responses when using [findOrFail()].
如果没有捕获到异常,则会自动向用户发送 404 HTTP 响应,因此在使用 [findOrFail()] 时无需编写显式检查以返回 404 响应。
Also, I'm pretty sure you get the exception page instead of 404 now because you're in debug mode.
另外,我很确定您现在得到的是异常页面而不是 404,因为您处于调试模式。
回答by Amitesh
findOrFail()is alike of find()function with one extra ability - to throws the Not Found Exceptions
findOrFail()类似于find()函数,但具有一项额外功能 - 抛出 Not Found Exceptions
Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The findOrFail and firstOrFail methods will retrieve the first result of the query; however, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundExceptionwill be thrown:
有时,如果找不到模型,您可能希望抛出异常。这在路由或控制器中特别有用。findOrFail 和 firstOrFail 方法将检索查询的第一个结果;但是,如果未找到结果,则会抛出Illuminate\Database\Eloquent\ModelNotFoundException:
$model = App\Flight::findOrFail(1);
$model = App\Flight::where('legs', '>', 100)->firstOrFail();
If the exception is not caught, a 404 HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return 404 responses when using these methods:
如果未捕获到异常,则会自动向用户发送 404 HTTP 响应。使用这些方法时,没有必要编写显式检查来返回 404 响应:
Route::get('/api/flights/{id}', function ($id) {
return App\Flight::findOrFail($id);
});
Its not recommended but If still you want to handle this exception globally, following are the changes as per your handle.php
不推荐但如果您仍然想全局处理此异常,以下是根据您的 handle.php 进行的更改
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
if ($exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
//redirect to errors.custom view page
return response()->view('errors.custom', [], 404);
}
return parent::render($request, $exception);
}
回答by Edwin Krause
Late addition to above topic: If you want to handle the exception for an API backend and you don't want to make the check for an empty result in each method and return a 400 Bad request error individually like this...
上述主题的后期补充:如果您想处理 API 后端的异常,并且不想在每个方法中检查空结果并像这样单独返回 400 Bad request 错误...
public function open($ingredient_id){
$ingredient = Ingredient::find($ingredient_id);
if(!$ingredient){
return response()->json(['error' => 1, 'message' => 'Unable to find Ingredient with ID '. $ingredient_id], 400);
}
return $ingredient;
}
Instead use findOrFail
and catch exception in app/Exceptions/Handler.php
.
而是findOrFail
在app/Exceptions/Handler.php
.
public function render($request, Exception $exception)
{
if ($exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
return response()->json(['error'=>1,'message'=> 'ModelNotFoundException handled for API' ], 400);
}
return parent::render($request, $exception);
}
This will then look like this in your Controllers:
这将在您的控制器中看起来像这样:
public function open($ingredient_id){
return Ingredient::findOrFail($ingredient_id);
}
which is much cleaner. Consider that you have plenty of Models and plenty of Controllers.
这更干净。考虑到您有大量模型和大量控制器。
回答by Iklan Hits
public function singleUser($id)
{
try {
$user= User::FindOrFail($id);
return response()->json(['user'=>user], 200);
} catch (\Exception $e) {
return response()->json(['message'=>'user not found!'], 404);
}
}