简体   繁体   中英

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?

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:

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

Why not use a php default paramenter value?

// 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.

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:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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