简体   繁体   English

Laravel-如何从Rout上的固定URL向控制器传递固定值

[英]Laravel - How to pass a fixed value to controller from a fixed url on rout

I want to pass an ID "0" to the controller if my url is user/new, how can i do it on the route.php in laravel? 如果我的网址是user / new,我想将ID“ 0”传递给控制器​​,如何在laravel中的route.php上执行此操作?

I imagined something like this, but I don't think is that simple. 我曾想过像这样的事情,但我认为不是那么简单。

Route::get('user/new','UserController@edit', ['id'=>'0']);
Route::get('user/edit/{id}','UserController@edit');

With normal .htaccess i'd do something like this: 使用正常的.htaccess,我会执行以下操作:

RewriteRule ^user/new    /www/user/edit.php?id=0        [L,QSA]
RewriteRule ^user/(.*)    /www/user/edit.php?id=$1      [L,QSA]

Do I need a middleware? 我需要中间件吗? Is there a more simple way to do it? 有更简单的方法吗?

That's semantically weird, creating an user with an edit function, anyways... 从语义上讲,这很奇怪,无论如何创建具有edit功能的用户……

Why not use a php default paramenter value? 为什么不使用php默认参数值呢?

// UserController.php

public function edit($id = 0) // NOTICE THIS
{
  // your id is zero if none passed (when /new is called)
}

Your already existing edit wouldn't change and you don't have to touch your routes. 您已经存在的edit不会更改,您也不必触摸路线。

One way would be to use a closure in your routes, like this: 一种方法是在路由中使用闭包,如下所示:

Route::get('user/new', function() {
    return App::make('UserController')->edit(0);
});

But the Laravel way would be to use RESTful resource controllers , which makes routes for create, edit and delete for you: 但是Laravel的方式是使用RESTful资源控制器 ,它为您创建,创建和删除路由:

Route::resource('user', 'UserController');

Im not sure why you want to do this, but you can do something like this in your controller: 我不确定为什么要这样做,但是可以在控制器中执行以下操作:

function newuser()
{
    return $this->edit(0);
}

function edit($id)
{
    // Do stuff
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM