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

Dar*_*ber 2 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);
}
Run Code Online (Sandbox Code Playgroud)

UsersController看起来像这样:

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

如果我访问上面的代码http://my.url/users/10/edit我得到NotFoundHttpException in Application.php line 901:,是的,因为我的记录中没有id 10,但是User::find($id);我得到没有数据的普通视图,因为我的记录中没有id 10.

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

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

ps: .env APP_DEBUG = true

ber*_*nie 12

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

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']));
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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


Ami*_*esh 5

findOrFail()类似于find()函数,但具有一项额外功能 - 抛出 Not Found Exceptions

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

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

$model = App\Flight::where('legs', '>', 100)->firstOrFail();
Run Code Online (Sandbox Code Playgroud)

如果未捕获到异常,则会自动向用户发送 404 HTTP 响应。使用这些方法时,没有必要编写显式检查来返回 404 响应:

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

不推荐但如果您仍然想全局处理此异常,以下是根据您的 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);
}
Run Code Online (Sandbox Code Playgroud)


小智 5

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);
    }
}
Run Code Online (Sandbox Code Playgroud)