Ilias Kouroudis
Ilias Kouroudis

Reputation: 356

Dynamically generate URL in Laravel

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

Upvotes: 2

Views: 3798

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152860

Instead of using a redirect you need to generate the real url right away.
I would add this method to your model class

class Article extends Eloquent {

    public function getUrl(){
        $cat = $this->category()->pluck('text');
        $shorturl = $this->urltext;
        $id = $this->id;

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

}

And then just call it on the article object $article->getUrl() to generate the url

Upvotes: 2

Related Questions