Laravel blade templates, foreach variable inside U

2019-04-20 09:06发布

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?

7条回答
我命由我不由天
2楼-- · 2019-04-20 09:20

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

查看更多
Emotional °昔
3楼-- · 2019-04-20 09:27

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>
查看更多
Evening l夕情丶
4楼-- · 2019-04-20 09:32

I think this will work

<a href="{{ url('test/'.$post->id.'/view') }}"></a>
查看更多
相关推荐>>
5楼-- · 2019-04-20 09:33

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") }}

查看更多
劳资没心,怎么记你
6楼-- · 2019-04-20 09:34

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>
查看更多
▲ chillily
7楼-- · 2019-04-20 09:35

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 }}

查看更多
登录 后发表回答