在Laravel中动态生成URL

I am using Laravel 4 for a new project, which is a news site.

The URL for a single article should be like this:

domain.com/{category}/{shorturl}/{id}

(for example "domain.com/sports/realmadrid-barcelona/15")

In my routes.php file I have declared:

Route::get('{cat}/{shorturl}/{id}', 'ArticlesController@view');

which is working fine.

Now all I need to do is use a single Article (model) instance to pass as parameter in the Controller action to generate the URL/Route. This means, instead of passing all three parameters ('cat', 'shorturl' and 'id'), I would like to pass the Article instance.

To manage this, what I did so far is the following:

In routes.php:

Route::model('article', 'Article');

Route::get('{cat}/{shorturl}/{id}', 'ArticlesController@view');
Route::get('article/{article}', 'ArticlesController@generateUrl');

In ArticlesController.php:

public function view($cat, $urltext, $id)
{
    $article = Article::findOrFail($id);
    return View::make('articleView', compact(array('article')));
}

public function generateUrl(Article $article)
{
    $cat = $article->category()->pluck('text');
    $shorturl = $article->urltext;
    $id = $article->id;

    return Redirect::action('ArticlesController@view', array('cat' => $cat, 'shorturl' => $shorturl, 'id' => $id));
}

By doing this, in my view file I have something like this to produce links to other articles:

<a href="{{ action('ArticlesController@generateUrl', $otherarticle) }}">{{ $otherarticle->title }}</a>

The problem is that, although the redirect works, the actual URL (the one shown on mouse hover) is the 'original' one (this means: "domain.com/article/123") instead of the intended ("domain.com/sports/realmadrid-barcelona/123").

Any ideas on how to accomplish this? I would like to only use $article (the Article model instance) to generate URLs, in order to keep the code as simple and clean as possible.

Thank you, Ilias

查看全部
duanli6618
联系Q1724651464
2014/11/20 10:56
  • laravel
  • php
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复