Reputation: 51
I'm trying to learn Laravel and I have some questions.
Let's say I have a route on home:
Route::('/', 'Home@index');
In Home View I have a link that takes me to /items/bananas and a link that takes me to /items/apples. SO i have to make another route like this:
Route::('items/{item_name}', 'Fruit@index');
On home I populate the links from the database. Like:
<a href="{{ $fruit->slug }}">{{ $fruit->name }}</a>
My question is, when I go from INDEX to /items/banana for example, how do I pass the $fruit object from Home View to Fruit View?
Upvotes: 0
Views: 168
Reputation: 1551
You misunderstand Http here (Or maybe I understood the question wrong at first). When you make the first request to your website (the '/' route) The webserver processes that request and serves the website, html, and your browser interprets it and generates what you see, that's it.
When you click a link another request is made and the server processes again (there are other ways to do this with JS differently but let's keep it simple).
So you can't pass anything from one Controller to another when you talk about it this way. What you want is getting the {item_name}
in the Controller because the link privides that information.
To achieve this Laravel makes it easy and you just define your FruitController method like so:
public function index($item_name){
// in $item_name you will have apple / banana
// so do something with it, like
$fruit = \App\Fruit::where('type', $item_name)->get();
}
Of course the logic inside the method depends on your setup and what you need to achieve. Enjoy.
Upvotes: 0
Reputation: 2807
You don't need to pass anything from the home view to the fruits page if you can have access to the fruits data from the database. As I can see in your code, your links have access a $fruit variable. You might have gotten this object from the database. Now the home view has access to this variable if the variable is passed to it in the route definition of '/' as follows:
Route::get('/', function() {
$fruit = Fruit::find(1)
return View::make('index')->with('fruit', $fruit);
}
In the same way, you can pass a fruit variable to every fruit page by specifying the id of the specific fruit:
Route::get('fruit/{id}', function($id) {
$fruit = Fruit::find($id);
return View::make('index')->with('fruit', $fruit);
})->where('id', '[0-9]+');
When you want to give a link to a fruit page for a specific fruit then in the index view you can compose the link using the url helper function "URL::to" as follows
<a href="{{ URL::to('/fruit/'.$fruit->id) }}">{{ $fruit->name }}</a>
The id will tell the fruit controller or route which fruit to retrieve from the database.
I hope this helps
Upvotes: 0
Reputation: 3930
You don't. You retrieve it from your data store
class FruitController
function indexAction($slug)
$fruit = Fruit::find...
Upvotes: 1