How to pass two arguments id and slug with url (routing) in laravel 5.1

て烟熏妆下的殇ゞ 提交于 2019-12-11 12:11:36

问题


It's very simple But I don't know how? I want to show post id and slug in URL like "http://localhost:8000/blog/27/this-is-test-post" but it's not working

My route

Route::get('blog/{id}/{slug}',['as'=>'blog.single','uses'=>'PageController@getSingle']);

My Controller

public function getSingle($id)
{
 $article=Article::where('id','=','$id')->first();
 return view('/articles/article')->withArticle($article);
}

"i want to fetch data by id so i use here only id"

My View

when i Use this, URL is Perfect but it's show Error "Trying to get property of non-object"

<a href="blog/{{$article->id}}/{{$article->slug}}" > {{$article->title}}</a></h3>

when I use this

<a href="blog/{{$article->id}}{{$article->slug}}" > {{$article->title}}</a></h3>

then my URL like http://localhost:8000/blog/27this-is-test-post (without any Error)


回答1:


Use the route helper.

route('blog.single', ['id' => $article->id, 'slug' => $article->slug]);

In your link:

<a href="{{ route('blog.single', ['id' => $article->id, 'slug' => $article->slug]) }}">{{ $article->title }}</a>



回答2:


You can use route helper

route('blog.single', ['id' => $article->id, 'slug' => $article->slug]);

Or define 2 parameters in controller method i.e

public function getSingle($id,$slug)
 {
  $article=Article::where('id','=','$id')->first();
  return view('/articles/article')->withArticle($article);
 }

because you have defined 2 parameters in route. Try it will work fine. You have to use route helper for generating url for form action or link href where you want to place it for click or post i.e

<a href='{{ route('folders.list') }}'>Folders</a> 

or

{{ route('folders.list',['id' => 1]) }} 

or you can also make your link as

<a href={{URL::to('blog/'.$article->id.'/'.$article->slug)}}>Some Link</a>

it will also work fine



来源:https://stackoverflow.com/questions/48815749/how-to-pass-two-arguments-id-and-slug-with-url-routing-in-laravel-5-1

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