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



我遵循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:使用控制器重定向页面,如果post不存在-尝试,但迄今为止失败):

use IlluminateDatabaseEloquentModelNotFoundException; // 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(IlluminateDatabaseEloquentModelNotFoundException $e)代替catch(ModelNotFoundException $e): no way
  2. use IlluminateDatabaseEloquentModelNotFoundException;放在模型中而不是控制器
  3. 返回一个简单的return 'fail';而不是return Redirect::action('GamesController@index');,看看问题是否在那里

  4. 把这段代码放在Laravel文档中建议的几乎所有地方

    App::error(function(ModelNotFoundException $e)
    {
        return Response::make('Not Found', 404);
    });
    

好吧,只是没有发生:我的错误仍然存在

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

  1. http://www.iwstudio.it/laravelerrors/01.png
  2. http://www.iwstudio.it/laravelerrors/02.png
请问,谁能告诉我我错过了什么?这简直要把我逼疯了……

提前感谢!

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

最直接的解决问题的方法是使用->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模型绑定,我注意到你可能已经在你的路由中使用了模型绑定:

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

所以在你定义模型绑定的某个地方,你可以添加闭包来处理错误:

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

第三种解决方案

在你的屏幕截图中,你的App::error似乎可以工作,因为错误说HttpNotFound Exception,这是Laravel说404错误的方式。所以最后一个解决方案是在那里写你的重定向,虽然这适用于全局(所以非常不鼓励)。

相关内容

最新更新