Laravel 4:重定向如果项目不存在,ModelNotFoundException无论如何都不起作用我尝试了

时间:2014-08-21 09:38:15

标签: laravel laravel-4

我正在关注Dayle Rees的书“Code Bright”关于使用Laravel(Playstation Game Collection)构建基本应用程序的教程。

到目前为止,该应用程序正在运行,但是,根据他在本章末尾的建议,我正在做我的作业,试图改进它

因此,此代码段适用于现有模型,但如果该项不存在则会引发错误:

public function edit(Game $game){
    return View::make('/games/edit', compact('game'));
}

换句话说,http://laravel/games/edit/1显示ID = 1的项目,但http://laravel/games/edit/21456会抛出错误,因为没有带有该ID的项目

让我们改进这种行为,调整StackOverflow(Laravel 4: using controller to redirect page if post does not exist - tried but failed so far)上的一些脚本:

use Illuminate\Database\Eloquent\ModelNotFoundException; // top of the page
...
public function edit(Game $game){
    try {
        $current = Game::findOrFail($game->id);
        return View::make('/games/edit', compact('game'));
    } catch(ModelNotFoundException $e) {
        return Redirect::action('GamesController@index');
    }
}

嗯......没有任何反应!我仍然有错误没有重定向到动作'GamesController @ index'...请注意我的控制器中没有名称空间

我几乎尝试过任何事情:

  1. catch(ModelNotFoundException $e)替换为catch(Illuminate\Database\Eloquent\ModelNotFoundException $e):没办法
  2. use Illuminate\Database\Eloquent\ModelNotFoundException;放入模型而不是控制器
  3. 返回一个简单的return 'fail';而不是return Redirect::action('GamesController@index');来查看问题是否存在

  4. 几乎放在Laravel documentation

    中建议的这个代码段的所有位置
    App::error(function(ModelNotFoundException $e)
    {
        return Response::make('Not Found', 404);
    });
    
  5. 好吧,只是没有发生了:我的错误仍在那里

    想看吗?以下是错误堆栈中的前两项:

    1. http://www.iwstudio.it/laravelerrors/01.png
    2. http://www.iwstudio.it/laravelerrors/02.png
    3. 请有人告诉我,我错过了什么?这让我很生气...

      提前致谢!

1 个答案:

答案 0 :(得分:0)

以下是我的一些解决方案:

第一个解决方案

对您的问题最直接的解决方法是使用->find()代替->findOrFail()

public function edit(Game $game){
    // Using find will return NULL if not found instead of throwing exception
    $current = Game::find($game->id);

    // If NOT NULL, show view, ELSE Redirect away
    return $current ? View::make('/games/edit', compact('game')) : Redirect::action('GamesController@index');
}

第二个解决方案

正如我所注意到的,你可能一直在使用模型绑定到你的路线,根据Laravel Route model binding

  

注意:如果在数据库中找不到匹配的模型实例,则会抛出404错误。

因此,在定义模型绑定的地方,可以添加闭包来处理错误:

Route::model('game', 'Game', function()
{
    return Redirect::action('GamesController@index');
});

第三种解决方案

在屏幕截图中,您的App::error似乎有效,因为错误显示为HttpNotFound Exception,这是Laravel说404错误的方式。因此,最后一个解决方案是在那里编写重定向,尽管这适用于全局(非常不鼓励)。