Laravel blade templates, foreach variable inside URL::to?

强颜欢笑 提交于 2019-12-10 01:47:35

问题


I'm creating a basic list view of posts, and need a link to the 'edit' page.

I'm using blade, and what I have is a table, with a foreach loop, showing each post along with edit/delete buttons.

What I wanted to do is use blade's URL::to for the links to the edit and delete pages, to ensure consistant links.

The code I've tried using (remember this is inside a foreach loop hence the $post->id var) is this:

<a href="{{ URL::to('admin/posts/edit/$post->id') }}" class="btn btn-mini btn-primary">Edit Post</a>

However this does not work. I've also tried

<a href="{{ URL::to('admin/posts/edit/<?php echo $post->id; ?>') }}" class="btn btn-mini btn-primary">Edit Post</a>

which also doesnt work.

I dont get any error, the link literally ends up being:

http://domain.dev/admin/posts/$post->id

Is there any way of working around this?


回答1:


I think the problem is that you are using php variable ($post) within a string with a single '. In this case it just outputs the name of the variable. Try this:

<a href="{{ URL::to('admin/posts/edit/' . $post->id) }}" class="btn btn-mini btn-primary">Edit Post</a>

Hope this helps. Vlad




回答2:


vlad has already given the right answer to your question but be aware that you can also directly link to your controller action via URL::action:

<a href="{{ URL::action('Admin\PostsController@edit', $post->id) }}">Edit</a>



回答3:


The {{ }} are equal to <?php echo ;?>

if you put single '

<?php echo '$hello' ?> = $hello

but if you put double ' (") -> <?php "$hello" ;?> = Hello World (just one example)

You need to write something like {{ URL::to("admin/posts/edit/$post->id") }}




回答4:


I think this will work

<a href="{{ url('test/'.$post->id.'/view') }}"></a>



回答5:


Another way

<a href="{{URL::to('/')}}/admin/posts/edit/{{$post->id}}">Edit</a>



回答6:


Had an issue with this in Laravel 5 so thought Id pop it in even if the question is old. Resolved my issue using

{{ URL::to('/box').'/'.$box->id }}

or
{{ url('/box').'/'.$box->id }}




回答7:


Also you may use route() helper to generate url by name of route. For example, definition of route:

Route::get('/test/mypage/{id}', 'MyController@myAction')->name('my_route_name');

Code in your view:

<a href="{{ route('my_route_name', $row['id']) }}">{{ $row['name'] }}</a>


来源:https://stackoverflow.com/questions/16506894/laravel-blade-templates-foreach-variable-inside-urlto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!