uberHasu
uberHasu

Reputation: 101

How to pass route values to controllers in Laravel 4?

I am struggling to understand something that I am sure one of you will be able to easily explain. I am somewhat new to MVC so please bear with me.

I have created a controller that handles all of the work involved with connecting to the Twitter API and processing the returned JSON into HTML.

Route::get('/about', 'TwitterController@getTweets');

I then use:

return View::make('templates.about', array('twitter_html' => $twitter_html ))

Within my controller to pass the generated HTML to my view and everything works well.

My issue is that I have multiple pages that I use to display a different Twitter user's tweets on each page. What I would like to do is pass my controller an array of values (twitter handles) which it would then use in the API call. What I do not want to have to do is have a different Controller for each user group. If I set $twitter_user_ids within my Controller I can use that array to pull the tweets, but I want to set the array and pass it into the Controller somehow. I would think there would be something like

Route::get('/about', 'TwitterController@getTweets('twitter_id')');

But that last doesn't work.

I believe that my issue is related to variable scope somehow, but I could be way off.

Am I going down the wrong track here? How do I pass my Controllers different sets of data to produce different results?

EDIT - More Info

Markus suggested using Route Parameters, but I'm not sure that will work with what I am going for. Here is my specific use case.

I have an about page that will pull my tweets from Twitters API and display them on the page. I also have a "Tweets" page that will pull the most recent tweets from several developers accounts and display them.

In both cases I have $twitter_user_ids = array() with different values in the array.

The controller that I have built takes that array of usernames and accesses the API and generates HTML which is passed to my view.

Because I am working with an array (the second of which is a large array), I don't think that Route Parameters will work.

Thanks again for the help. I couldn't do it without you all!

Upvotes: 2

Views: 6655

Answers (1)

Markus Hofmann
Markus Hofmann

Reputation: 3447

First of all, here's a quick tip:

Instead of

return View::make('templates.about', array('twitter_html' => $twitter_html ))

...use

return View::make('templates.about', compact('twitter_html'))

This creates the $twitter_html automatically for you. Check it out in the PHP Manual.

 

Now to your problem:

You did the route part wrong. Try:

Route::get('/about/{twitter_id}', 'TwitterController@getTweets');

This passes the twitter_id param to your getTweets function.

Check out the Laravel Docs: http://laravel.com/docs/routing#route-parameters

Upvotes: 2

Related Questions