当表中不存在资源时,如何重新路由到另一个视图(Laravel 4)



我有一个资源:

Route::resource('artists', 'ArtistsController');

对于特定的url (domain.com/artists/{$id}或domain.com/artists/{$url_tag}),我可以在表artists中查看单个页面中的资源。它由以下函数控制:

public function show($id)
    {
        if(!is_numeric($id)) {
                $results = DB::select('select * from artists where url_tag = ?', array($id));
                if(isset($results[0]->id) && !empty($results[0]->id)) {
                    $id = $results[0]->id;
                }
            }
            else {
                $artist = Artist::find($id);  
            }
        $artist = Artist::find($id);
        return View::make('artists.show', compact('artist'))
            ->with('fans', Fan::all())
            ->with('friendlikes', Fanartist::friend_likes())
            ->with('fan_likes', Fanartist::fan_likes());
    }

我想做的是有所有访问的url,其中{$id}或{$url_tag}不存在于表中,被重路由到另一个页面。例如,如果我输入domain.com/artists/jujubeee,而$url_tag列的表中不存在jujubee,我希望将其重路由到另一个页面。

有什么好主意吗?

谢谢。

在您的show方法中,您可以使用如下内容:

public function show($id)
{
    $artist = Artist::find($id);
    if($artist) {
        return View::make('artists.show', compact('artist'))->with(...)
    }
    else {
        return View::make('errors.notfound')->withID($id);
    }
}

在您的views文件夹中创建一个名为errors的文件夹(如果不存在),并在此文件夹中创建一个名为notfound.blade.phpview,在此视图文件中,您将获得$id,因此您可以在有/没有id的情况下显示有用的东西。

或者,您可以在app/start/global.php文件中注册一个全局NotFoundHttpException异常处理程序,如下所示:

App::error(function(SymfonyComponentHttpKernelExceptionNotFoundHttpException $e) {
    // Use $e->getMessage() to get the message from the object
    return View::make('errors.notfound')->with('exception', $e);
});

要重定向到另一个页面,请查看Laravel文档的响应页面中可用的重定向方法。

这是我将如何去做,并注意,你也可以简化你的数据库查询使用Eloquent:

public function show($id)
{
    if( ! is_numeric($id)) {
        // Select only the first result. 
        $artist = Arist::where('url_tag', $id)->first();
    }
    else {
        // Select by primary key
        $artist = Artist::find($id);  
    }
    // If no artist was found
    if( ! $artist) {
        // Redirect to a different page.
        return Redirect::to('path/to/user/not/found');
    }
    return View::make('artists.show', compact('artist'))
        ->with('fans', Fan::all())
        ->with('friendlikes', Fanartist::friend_likes())
        ->with('fan_likes', Fanartist::fan_likes());
}

最新更新