如何将链接中的变量传递给laravel中的控制器?

时间:2016-04-13 16:19:18

标签: php laravel

所以我有一个包含项目表的页面设置。每行都有一个链接。单击链接时,我想将它们的ID传递给控制器​​,以便将其传递给另一个视图。虽然我无法弄清楚如何做到这一点。

这是我的项目视图中的代码

                @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

正如您所看到的,有一个链接可以将我引导至租金视图。在控制器中,这就是我所拥有的一切。

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

感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

您可以使用route()帮助:

@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

作为替代方案,您可以使用链接操作:

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

有时候使用url()帮助器是有用的:

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

有关这些helpes的更多信息here

如果您正在使用安装了Laravel Collective的Laravel 5,或者您使用的是Laravel 4,则可以使用these constructions生成带参数的网址。

PS:如果您使用表格进行布局,请不要这样做。你应该学习DIV,因为使用内置Laravel的Bootstrap框架,使用DIV构建很酷的布局真的很容易。

答案 1 :(得分:0)

我可能会这样做。

@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

然后在你的控制器内,你可以接受你传递的价值。

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

然后在你的new-view.blade.php

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

在此处阅读有关Laravel网址助手的更多信息https://laravel.com/docs/5.1/helpers#urls