2

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.