欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

resource route parameter 路由参数 找 except 有大用 有大大用 有大大大用



下面第一个是我自己亲自做的 Laravel 5.6 additional Route::resource() Parameters    

up vote1down votefavorite                

I would like to know how to add additional parameters to Laravel's Route Resource without using Query Strings.

I created a controller (CustomerController) with all the built-in resources and then, added the following route:

Route::resource('customers', 'CustomerController');
                   

What i would like to do is add additional parameters to some of the default resources without creating custom routes or using query strings. For example:

Default resource with optional parameter (index):

public function index($page = 0)
{
    //...
}
                   

Desired URL:

http://www.example.com/customers
http://www.example.com/customers/{page}
                   

I tried the following, but i get a not found exception (NotFoundHttpException):

Route::resource('customers', 'CustomerController')->parameters([
    'index' => 'page'
]);
                   

Is this possible? If so, how can i accomplish it?

                      
shareimprove this question                            
asked Apr 16 at 22:56                                
                                   
                               
Ricky                                    
72421331                                    
  • 1                                
    This goes against how resources work in Laravel. You can exclude the routes you want to override and define them manually. Remember, Laravel is opinionated, but you can change it's opinion whenever you please. – Ohgodwhy Apr 16 at 23:12                                 
       

1 Answer 正确答案            

activeoldestvotes                    
       
up vote3down voteaccepted                    

Resource Controllers must implement a defined set of methods which are then mapped to the appropriate HTTP verb and path by the router. These methods, paths and verbs form part of a contract that cannot be adjusted, otherwise working with a Laravel application that implements Resource Controllers would be a headache.

Resource Controllers excel in providing the same experience across all Laravel applications, if your application requires behaviour that isn't supported out of the box by Resource Controllers then it is a sign that you should not be using them and should instead register your routes manually.

If you have just one route that needs to implement custom behaviour then you can register somemethods instead of all and then choose to register a custom route to your Resource Controllers method, something like:

Route::resource('customers', 'CustomerController')->except([
    'index'
]);

Route::get('/customers/{page?}', 'CustomerController@index');

                       

Route::controller 好像 不行  (下面的我自己亲自做的,但是应该不行)  (就是对index 不管用,只有把 controller/index 使用起来才行,下面的配置就不需要了)  


Route::get('common-user/order/{order_state?}','CommonUser\OrderController@getIndex')->where('order_state','[0-9]+');
Route::controller('common-user/order','CommonUser\OrderController');

Route::get('common-user/{order_state?}','CommonUser\OrderController@getIndex')->where('order_state','[0-9]+');
Route::controller('common-user','CommonUser\OrderController');


The documentation on Resource Controllers covers except and only.

shareimprove this answer                            
answered Apr 16 at 23:12                                
                                   
                               
sam                                    
2,71041841                                    
  • Hi @sam, thanks for the detailed explanation. I'm using resources because i really don't need any extra features other than the ones provided by Laravel. In this case i'm going use your approach. Once again thanks :) – Ricky Apr 17 at 15:21                                    
       

来自  https://stackoverflow.com/questions/49867423/laravel-5-6-additional-routeresource-parameters            


           

Passing 2 Parameters to Laravel Routes - Resources                

Ask Question                
up vote7down votefavorite                                
4                                

I'm trying to build my routes using resources so that I can pass two parameters into my resources.

I'll give you a few examples of how the URLS would look:

domain.com/dashboard
domain.com/projects
domain.com/project/100
domain.com/project/100/emails
domain.com/project/100/email/3210
domain.com/project/100/files
domain.com/project/100/file/56968
                               

So you can see I always need to have reference to the project_id and also the email/file id etc.

I realize I can do this manually by writing all routes by hand, but I'm trying to stick to the resource model.

I figured something like this might work?

Route::group(['prefix' => 'project'], function(){
  Route::group(['prefix' => '{project_id}'], function($project_id){

    // Files
    Route::resource('files', 'FileController');

  });
});
                           
                                   
shareimprove this question                                        
asked Nov 27 '14 at 10:32                                            
                                               
                                           
amof                                                
141514                                                
                   

2 Answers   正确答案                            

activeoldestvotes                                
                   
up vote9down voteaccepted                                

As far as I know about resources

Route::resource('files', 'FileController');
                                   

The above mentioned resource will route the following urls.

Few Actions Handled By Resource Controller for your Route::resource('files', 'FileController');                                    

Route::get('files',FileController@index) // get req will be routed to the index() function in your controller
Route::get('files/{val}',FileController@show) // get req with val will be routed to the show() function in your controller
Route::post('files',FileController@store) // post req will be routed to the store() function in your controller
Route::put('files/{id}',FileController@update) // put req with id will be routed to the update() function in your controller
Route::delete('files',FileController@destroy) // delete req will be routed to the destroy() function in your controller
                                   

the single resource Mentioned above will do all the listed routing                                    

Apart from those you have to write your custom route                                    

In your scenario of

Route::group(['prefix' => 'project'], function(){
  Route::group(['prefix' => '{project_id}'], function($project_id){

    // Files
    Route::resource('files', 'FileController');

  });
}); 
                                   

domain.com/project/100/files 

if its a get request will be routed to FileController@index
if its a post request will be routed to FileController@store                                    

if your "domain.com/project/100/file/56968" is changed to "domain.com/project/100/files/56968" (file to files)then the following rooting will occur...

domain.com/project/100/files/56968

if its a get request will be routed to FileController@show
if its a put request will be routed to FileController@update
if its a delete request will be routed to FileController@destroy                                    

and it has no impact on any other urls you have mentioned

Provided, you need to have RESTful Resource Controllers                                    

shareimprove this answer                                        
edited Dec 6 '14 at 10:07                                            
answered Nov 27 '14 at 11:07                                            
                                               
                                           
Ronser                                                
1,26831435                                                
  • 1                                                
    That explains it well, I didn't realise this would pass the project id through to method as well, but it does indeed appear to work. Thanks! – amof Nov 27 '14 at 12:14                                                
                   
up vote5down vote                                

For the request like '/project/100/file/56968', you must specify your route like this:

Route::resource('project.file', 'FileController');
                                   

And then you can get parameters at the show method of the controller:

public function show($project, $file) {
    dd([
        '$project' => $project,
        '$file' => $file
    ]);
}
                                   

The result of this example will be:

array:2 [▼
  "$project" => "100"
  "$file" => "56968"
]
                               
shareimprove this answer                                        
edited Aug 17 '15 at 23:03                                            
answered Aug 17 '15 at 22:53                                            
                                               
                                           
zhekaus                                                
1,49911236                                                
                   

来自  https://stackoverflow.com/questions/27168425/passing-2-parameters-to-laravel-routes-resources                    


                   






大厦大厦大厦大厦大厦大厦大厦大厦大厦大厦大厦大厦大厦大厦大厦大厦大厦大厦


I trying to make this REST design but I am having trouble.

I have a resource called list

I want before /list it to have a dynamic parameter like so {username}/list and the have the CRUD options like edit {username}/list/{id}/edit and so on.

1 Answer 正确答案 

Using the ::resource method you can dictate the hierarchical route pattern by using a . between your models, for instance:

Route::resource('user.list', 'ListController');

This will produce something like this:

/user/{user}/list/{list}

However you want to have a username - which is fine, we just need to add some explicit model binding in your App\Providers\RouteServiceProvider

Route::bind('user', function($value)(){
    if(is_numeric($value)) {
        return User::find($value);
    } else { 
        return User::where('username', $value)->first();
    }
});

Adding this explicit model binding will attempt to resolve the user over dependency injectionfirst by ID if the $value is numeric. If not, then it will attempt to match the value against the username column on the user table.

Hopefully this helps.

来自   https://stackoverflow.com/questions/32605648/laravel-5-routeresource-to-get-three-parameters


来自 

https://github.com/laravel/framework/issues/3549



Resourceful controllers: overriding route names and parameters

Resource controllers are amazing tool to work with CRUD functions in Laravel. But what if their default functionality isn’t 100% suitable and you want to override some defaults? Let’s see what you can do.

Overriding route names

Default functionality in routes:



It will assume that controller will have these methods:

  • index()

  • create()

  • store()

  • edit()

  • update()

  • show()

  • destroy()

And the same will apply to route names – they will be assigned as photo.createphoto.showetc. So what if you want to override them? There’s a parameter for that.



In this case, photo.create will be replaced by photo.build, which now you can call in the links.


Overriding route parameters

Another assumption of Resource controllers are the variables for methods like show() or edit(). By default, the case of Route::resource(‘photo’, ‘PhotoController’); will generate route like this:



And you need to deal with $photo variable.
If, for whatever reason, you want to override it to $user_photo, you easily can:



I know that this overriding is probably quite an edge-case, but it was news for me, so decided to share.

This is one of the places in documentation which people don’t get to, until they need to solve that actual problem. And then they usually go to forums for the answer. Hopefully now they will google and land on this article.

Link to the official documentation.

Want to generate Laravel adminpanel online?
You don't need any packages to do that!

One thought on “Resourceful controllers: overriding route names and parameters

Leave a Reply

Your email address will not be published. Required fields are marked *

I'm using some web routes behind a resource controller. So the route looks simply like:

Route::resource('account', 'AccountController');

I also have a web middleware that checks if a user_id parameter is set in the Request object:

if ($request->user_id) {
    // do stuff
}

The problem is this. In my non-resource routes I use something like:

Route::get('agentnotes/{user_id}', 'UserNoteController@getUserNotes');

This sets the user_id variable as expected, and the middleware functions fine.

But in the resource routes, even though the actual route method uses the user_id, the middleware isn't seeing it. So for example, the AccountController::show method looks like this:

public function show($user_id)

But the middleware doesn't see that user_id as part of the request, I assume because it's already fired before the request gets to the controller.

Is there a way to handle this without rewriting all the resource routes?

1 Answer 正确答案

According to the Laravel docs:

By default, Route::resource will create the route parameters for your resource routes based on the "singularized" version of the resource name. You can easily override this on a per resource basis by passing parameters in the options array.

So I had to override the default values using my user_id that the middleware expected.

Route::resource('account', 'AccountController', ['parameters' => [
    'account' => 'user_id'
]]);


来自  https://stackoverflow.com/questions/46943393/laravel-5-override-route-resource-parameters


Defining optional parameters on a Route::resource #3549

 Closed
joshhornby opened this issue on 13 Feb 2014 · 6 comments

Comments

Projects
None yet
3 participants
@joshhornby@taylorotwell@anlutro
@joshhornby
Contributor

joshhornby commented on 13 Feb 2014

Would it be possible to attach an optional parameter in front of a route resource? I know you can do it manually by defining the routes but would be much cleaner to be able to just attach before the resource.

Something like this:

Route::group(array('prefix' => '/api/v2'), function() {
    Route::resource('{site?}/data', 'DataController')->where('site', '[0-9]+');
});
@taylorotwell
Member

taylorotwell commented on 13 Feb 2014

No you can't have an optional pattern followed by required patterns.

@anlutro
Contributor

anlutro commented on 13 Feb 2014

I tried to do something related to this, and I know that optional variables that aren't at the end of the URL are compiled automatically into non-optional ones by the Symfony Route class regex compiler, so this is not easily done for any route types.

@joshhornby
Contributor

joshhornby commented on 13 Feb 2014

Can you have an optional parameter with out having the required pattern?

@anlutro
Contributor

anlutro commented on 13 Feb 2014

Not for Route::resource, but for individual routes you can have as many optional parameters you want as long as they're at the end.

@joshhornby
Contributor

joshhornby commented on 13 Feb 2014

How about for route groups?

Route::group(array('prefix' => 'foo/{foo_id?}'), function() {
   Route::any('bar', 'ApiFooController@bar');
});
@anlutro
Contributor

anlutro commented on 13 Feb 2014

Route prefixes do not support parameters.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment




来自   https://github.com/laravel/framework/issues/3549




普通分类: