Jack O'Hara
Jack O'Hara

Reputation: 23

How do I pass a variable from a link to a controller in laravel?

So I have a page setup with a table of items. In each row there is a link. When the link is clicked I want to pass the ID of them through to the controller so I can pass it on to another view. Although I can't figure out how to do this.

This is the code in my item view

                @foreach($items as $item)
                <tr>
                        <td>{{$item->title}}</td>
                        <td>{{$item->genre}}</td>
                        <td>{{$item->description}}</td>
                        <td><a href="{{ url('/rent') }}">View</a></td>
                      </tr>
                @endforeach

As you can see there is a link which leads me to the rent view. In the controller this is all I have.

public function rent()
{  
    return view('rent');
}

Any help would be appreciated thanks.

Upvotes: 2

Views: 1393

Answers (2)

andrew-caulfield
andrew-caulfield

Reputation: 2070

I'd probably do it something like this.

@foreach($items as $item)
 <tr>
   <td>{{$item->title}}</td>
   <td>{{$item->genre}}</td>
   <td>{{$item->description}}</td>
   <td><a href="{{ route('/rent', [ 'id' => $item->valueYouWantToPass ])}}">View</a></td>
 </tr>
@endforeach

And then inside your controller you can accept the the value you are passing.

public function rent($value)
{
    return View::make('new-view')->with('value', $value);
}

and then inside your new-view.blade.php

<p> The value I passed is: {{ $value }} </p>

Read more about Laravel url helpers here https://laravel.com/docs/5.1/helpers#urls

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163788

You can use route() helper:

@foreach($items as $item)
    <tr>
        <td>{{ $item->title }}</td>
        <td>{{ $item->genre }</td>
        <td>{{ $item->description }}</td>
        <td><a href="{{ route('rent', ['id' => $item->someId]) }}">View</a></td>
    </tr>
@endforeach

As alternative you can use link to action:

{{ action('RentController@profile', ['id' => $item->someId]); }}

And sometimes it's useful to use url() helper:

{{ echo url('rent', [$item->someId]) }}

More on these helpes here.

If you're using Laravel 5 with Laravel Collective installed or you're on Laravel 4, you can use these constructions to generate URLs with parameters.

PS: If you're using tables for layout, don't do it. You should learn DIVs, because it's really easy now to build cool layout with DIVs using Bootstrap framework which is built-in Laravel.

Upvotes: 0

Related Questions