Laravel 5:如何使用findOrFail()方法?

时间:2015-09-23 11:01:21

标签: php laravel-5

我只是按照一些教程,到目前为止我所做的是:

我的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);
}

我的UsersController看起来像这样:

...
public function edit($id)
{
    $data = User::findOrFail($id);
    $roles = Role::where('title', '!=', 'Super Admin')->get();
    return View('admin.user.edit', compact(['data', 'roles']));
}
...

如果我访问http://my.url/users/10/edit,我会得到NotFoundHttpException in Application.php line 901:,是的,因为我的记录中没有ID 10,但是User::find($id);我没有数据就能获得正常视图,因为没有我记录中的ID为10。

我想要的是show default 404然后重定向到某个地方或者如果找不到User::findOrFail($id);的记录则返回一些内容?我怎么能这样做?

谢谢,任何帮助表示赞赏。

ps: .env APP_DEBUG = true

4 个答案:

答案 0 :(得分:11)

这就是你所要求的。无需例外。

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']));
    }
}

您的异常处理程序不是必需的。关于Illuminate\Database\Eloquent\ModelNotFoundException

  

如果未捕获到异常,则会自动将404 HTTP响应发送回用户,因此在使用[findOrFail()]时,无需编写显式检查以返回404响应。

另外,我很确定你现在得到异常页面而不是404,因为你处于调试模式。

答案 1 :(得分:2)

findOrFail() find()函数类似,但具有一项额外功能-引发未找到的异常

有时候,如果找不到模型,您可能希望抛出异常。这在路由或控制器中特别有用。 findOrFail和firstOrFail方法将检索查询的第一个结果。但是,如果未找到结果,则会抛出 Illuminate \ Database \ Eloquent \ ModelNotFoundException

$model = App\Flight::findOrFail(1);

$model = App\Flight::where('legs', '>', 100)->firstOrFail();

如果未捕获到异常,则会将404 HTTP响应自动发送回用户。使用这些方法时,无需编写显式检查以返回404响应:

Route::get('/api/flights/{id}', function ($id) {
    return App\Flight::findOrFail($id);
});

不建议这样做,但是如果仍然要全局处理此异常,则按照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);
}

答案 2 :(得分:0)

以上主题的最新补充:如果您要处理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;
}

请改为使用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);
}

然后在您的控制器中将如下所示:

public function open($ingredient_id){
    return Ingredient::findOrFail($ingredient_id);
}  

这更干净。考虑到您有大量的模型和大量的控制器。

答案 3 :(得分:0)

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);
    }
}