如何使用 Request $request 从 url 获取 id?(Laravel 5.3)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42848379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:35:15  来源:igfitidea点击:

How can I get id from url with Request $request? (Laravel 5.3)

phplaravelroutesrequestlaravel-5.3

提问by samuel toh

My link href on the view is like this :

我在视图上的链接 href 是这样的:

<a href="{{ route('message.inbox.detail.id', ['id' => $message->id]) }}" class="btn btn-default">
    <span class="fa fa-eye"></span> {{ trans('button.view') }}
</a>

My routes is like this :

我的路线是这样的:

Route::get('message/inbox/detail/id/{id}', ['as'=>'message.inbox.detail.id','uses'=>'MessageController@detail']);

When clicked, the url display like this :

点击后,网址显示如下:

http://myshop.dev/message/inbox/detail/id/58cadfba607a1d2ac4000254

I want get id with Request $request

我想得到身 Request $request

On the controller, I try like this :

在控制器上,我尝试这样:

public function detail(Request $request)
{
    dd($request->input('id'));
}

The result : null

结果:空

How can I solve it?

我该如何解决?

回答by Martynas A.

You can get it like this

你可以这样得到

$request->route('id')

Inside request class you can access it this way

在请求类中,您可以通过这种方式访问​​它

$this->route('id')

I usually use it when I'm validating field to make sure it's unique, and I need to exclude model by ID when I'm doing update

我通常在验证字段时使用它以确保它是唯一的,并且在我进行更新时需要按 ID 排除模型

回答by Irvin Chan

This is because you're passing the id parameter through url, you should send it using a form like this

这是因为您通过 url 传递 id 参数,您应该使用这样的表单发送它

{!! Form::open(['route'=>' route('message.inbox.detail.id', 'method'=> 'POST']) !!}
 <input type="hidden" name="id" value="{{ $message->id }}" />
{!! Form::submit({{ trans('button.view') }}, ['class'=>'btn btn-default']) !!}
{!! Form::close() !!}

and now you can access via request in your controller

现在您可以通过控制器中的请求访问

public function detail(Request $request)
{


 dd($request->input('id'));
}

回答by SteD

Get the id via this:

通过这个获取id:

public function detail($id)
{
   dd($id);
}