banner



How Do I Pass Route-id-name To Controller

Routing

  • Basic Routing
    • Redirect Routes
    • View Routes
    • The Route Listing
  • Route Parameters
    • Required Parameters
    • Optional Parameters
    • Regular Expression Constraints
  • Named Routes
  • Road Groups
    • Middleware
    • Controllers
    • Subdomain Routing
    • Road Prefixes
    • Road Name Prefixes
  • Road Model Binding
    • Implicit Binding
    • Implicit Enum Binding
    • Explicit Bounden
  • Fallback Routes
  • Rate Limiting
    • Defining Rate Limiters
    • Attaching Rate Limiters To Routes
  • Class Method Spoofing
  • Accessing The Current Route
  • Cross-Origin Resources Sharing (CORS)
  • Route Caching

Bones Routing

The virtually basic Laravel routes accept a URI and a closure, providing a very simple and expressive method of defining routes and behavior without complicated routing configuration files:

                                        

use Illuminate\Support\Facades\ Route ;

Route :: get ( ' /greeting ' , function () {

render ' Hi Globe ' ;

});

The Default Route Files

All Laravel routes are defined in your route files, which are located in the routes directory. These files are automatically loaded by your application's App\Providers\RouteServiceProvider. The routes/web.php file defines routes that are for your web interface. These routes are assigned the web middleware group, which provides features like session state and CSRF protection. The routes in routes/api.php are stateless and are assigned the api middleware group.

For well-nigh applications, you volition begin by defining routes in your routes/web.php file. The routes defined in routes/web.php may be accessed by inbound the defined road'southward URL in your browser. For example, you may admission the following route past navigating to http://instance.com/user in your browser:

                                        

use App\Http\Controllers\ UserController ;

Route :: become ( ' /user ' , [ UserController :: class , ' alphabetize ' ]);

Routes defined in the routes/api.php file are nested within a route group by the RouteServiceProvider. Inside this grouping, the /api URI prefix is automatically applied so you do non demand to manually utilize it to every road in the file. You may modify the prefix and other route grouping options by modifying your RouteServiceProvider class.

Available Router Methods

The router allows yous to register routes that respond to any HTTP verb:

                                        

Route :: become ( $uri , $callback );

Road :: post ( $uri , $callback );

Route :: put ( $uri , $callback );

Route :: patch ( $uri , $callback );

Road :: delete ( $uri , $callback );

Route :: options ( $uri , $callback );

Sometimes you may need to register a road that responds to multiple HTTP verbs. You may do and then using the lucifer method. Or, you may even register a road that responds to all HTTP verbs using the any method:

                                        

Route :: match ([ ' become ' , ' post ' ], ' / ' , function () {

//

});

Route :: any ( ' / ' , office () {

//

});

{tip} When defining multiple routes that share the same URI, routes using the get, mail service, put, patch, delete, and options methods should be divers before routes using the whatever, lucifer, and redirect methods. This ensures the incoming asking is matched with the correct road.

Dependency Injection

Yous may type-hint any dependencies required past your road in your route's callback signature. The declared dependencies will automatically exist resolved and injected into the callback past the Laravel service container. For example, yous may type-hint the Illuminate\Http\Request class to have the electric current HTTP request automatically injected into your route callback:

                                        

use Illuminate\Http\ Request ;

Route :: get ( ' /users ' , role ( Request $asking ) {

// ...

});

CSRF Protection

Recall, any HTML forms pointing to POST, PUT, PATCH, or DELETE routes that are defined in the web routes file should include a CSRF token field. Otherwise, the request will be rejected. You can read more most CSRF protection in the CSRF documentation:

                                        

< form method = " POST " activity = " /profile " >

@ csrf

...

< / course >

Redirect Routes

If you are defining a route that redirects to another URI, you may use the Route::redirect method. This method provides a convenient shortcut and then that you practise not have to define a full road or controller for performing a simple redirect:

                                        

Route :: redirect ( ' /here ' , ' /at that place ' );

By default, Route::redirect returns a 302 status code. You may customize the condition code using the optional tertiary parameter:

                                        

Route :: redirect ( ' /here ' , ' /there ' , 301 );

Or, yous may use the Route::permanentRedirect method to return a 301 condition code:

                                        

Route :: permanentRedirect ( ' /hither ' , ' /there ' );

{notation} When using route parameters in redirect routes, the following parameters are reserved by Laravel and cannot be used: destination and status.

View Routes

If your route only needs to return a view, y'all may utilize the Route::view method. Like the redirect method, this method provides a simple shortcut and then that y'all exercise not take to define a total route or controller. The view method accepts a URI as its first statement and a view name as its second argument. In addition, you may provide an array of data to pass to the view every bit an optional third statement:

                                        

Route :: view ( ' /welcome ' , ' welcome ' );

Route :: view ( ' /welcome ' , ' welcome ' , [ ' name ' => ' Taylor ' ]);

{notation} When using route parameters in view routes, the following parameters are reserved by Laravel and cannot be used: view, data, status, and headers.

The Road List

The route:list Artisan command can easily provide an overview of all of the routes that are divers past your application:

                                        

php artisan route:list

By default, the road middleware that are assigned to each route will not be displayed in the road:listing output; yet, you tin instruct Laravel to brandish the road middleware by adding the -v option to the control:

                                        

php artisan route:list -v

In add-on, you may instruct Laravel to hibernate any routes that are defined by tertiary-party packages by providing the --except-vendor option when executing the road:list command:

                                        

php artisan route:listing --except-vendor

Route Parameters

Required Parameters

Sometimes you will demand to capture segments of the URI within your route. For example, you lot may need to capture a user's ID from the URL. You may do so by defining road parameters:

                                        

Route :: get ( ' /user/{id} ' , part ( $id ) {

return ' User ' . $id ;

});

Y'all may define equally many route parameters as required by your road:

                                        

Route :: go ( ' /posts/{mail}/comments/{comment} ' , function ( $postId , $commentId ) {

//

});

Road parameters are always encased within {} braces and should consist of alphabetic characters. Underscores (_) are also acceptable within route parameter names. Route parameters are injected into road callbacks / controllers based on their order - the names of the route callback / controller arguments do non matter.

Parameters & Dependency Injection

If your route has dependencies that you would like the Laravel service container to automatically inject into your route'south callback, you should list your route parameters later your dependencies:

                                        

use Illuminate\Http\ Asking ;

Route :: go ( ' /user/{id} ' , office ( Asking $request , $id ) {

return ' User ' . $id ;

});

Optional Parameters

Occasionally you may need to specify a road parameter that may non e'er exist present in the URI. You may practice so by placing a ? mark after the parameter name. Brand sure to give the route's corresponding variable a default value:

                                        

Route :: go ( ' /user/{name?} ' , function ( $name = null ) {

return $proper name ;

});

Road :: get ( ' /user/{proper noun?} ' , function ( $name = ' John ' ) {

return $name ;

});

Regular Expression Constraints

You may constrain the format of your route parameters using the where method on a route instance. The where method accepts the proper noun of the parameter and a regular expression defining how the parameter should be constrained:

                                        

Route :: become ( ' /user/{name} ' , office ( $proper name ) {

//

}) -> where ( ' proper name ' , ' [A-Za-z]+ ' );

Route :: get ( ' /user/{id} ' , role ( $id ) {

//

}) -> where ( ' id ' , ' [0-9]+ ' );

Route :: go ( ' /user/{id}/{proper name} ' , function ( $id , $name ) {

//

}) -> where ([ ' id ' => ' [0-9]+ ' , ' name ' => ' [a-z]+ ' ]);

For convenience, some normally used regular expression patterns accept helper methods that permit you lot to rapidly add pattern constraints to your routes:

                                        

Route :: get ( ' /user/{id}/{name} ' , function ( $id , $proper name ) {

//

}) -> whereNumber ( ' id ' ) -> whereAlpha ( ' proper noun ' );

Road :: get ( ' /user/{proper name} ' , role ( $proper name ) {

//

}) -> whereAlphaNumeric ( ' name ' );

Route :: get ( ' /user/{id} ' , function ( $id ) {

//

}) -> whereUuid ( ' id ' );

Road :: get ( ' /category/{category} ' , function ( $category ) {

//

}) -> whereIn ( ' category ' , [ ' movie ' , ' vocal ' , ' painting ' ]);

If the incoming request does not match the route pattern constraints, a 404 HTTP response volition be returned.

Global Constraints

If you would like a route parameter to always be constrained past a given regular expression, you may utilise the pattern method. Y'all should define these patterns in the boot method of your App\Providers\RouteServiceProvider grade:

                                        

/**

* Define your route model bindings, pattern filters, etc.

*

* @return void

*/

public function boot ()

{

Route :: pattern ( ' id ' , ' [0-9]+ ' );

}

One time the blueprint has been defined, information technology is automatically applied to all routes using that parameter proper noun:

                                        

Route :: get ( ' /user/{id} ' , part ( $id ) {

// Only executed if {id} is numeric...

});

Encoded Frontward Slashes

The Laravel routing component allows all characters except / to be present within route parameter values. You must explicitly permit / to exist part of your placeholder using a where condition regular expression:

                                        

Route :: get ( ' /search/{search} ' , function ( $search ) {

return $search ;

}) -> where ( ' search ' , ' .* ' );

{note} Encoded forward slashes are merely supported within the last route segment.

Named Routes

Named routes permit the user-friendly generation of URLs or redirects for specific routes. You may specify a proper name for a road by chaining the name method onto the route definition:

                                        

Route :: become ( ' /user/contour ' , function () {

//

}) -> name ( ' contour ' );

You may besides specify route names for controller actions:

                                        

Route :: get (

' /user/profile ' ,

[ UserProfileController :: grade , ' bear witness ' ]

) -> name ( ' profile ' );

{note} Route names should always be unique.

Generating URLs To Named Routes

Once you have assigned a proper name to a given road, y'all may use the route's proper noun when generating URLs or redirects via Laravel's route and redirect helper functions:

                                        

// Generating URLs...

$url = road ( ' profile ' );

// Generating Redirects...

return redirect () -> route ( ' contour ' );

If the named road defines parameters, you may laissez passer the parameters every bit the second statement to the route role. The given parameters volition automatically exist inserted into the generated URL in their correct positions:

                                        

Road :: get ( ' /user/{id}/profile ' , function ( $id ) {

//

}) -> name ( ' profile ' );

$url = route ( ' profile ' , [ ' id ' => 1 ]);

If you pass additional parameters in the array, those key / value pairs volition automatically be added to the generated URL'south query cord:

                                        

Route :: go ( ' /user/{id}/profile ' , part ( $id ) {

//

}) -> proper name ( ' profile ' );

$url = route ( ' profile ' , [ ' id ' => ane , ' photos ' => ' yes ' ]);

// /user/one/profile?photos=yes

{tip} Sometimes, you may wish to specify request-broad default values for URL parameters, such equally the current locale. To attain this, you may use the URL::defaults method.

Inspecting The Current Road

If you would like to decide if the current request was routed to a given named road, y'all may use the named method on a Route example. For instance, you lot may check the current route name from a route middleware:

                                        

/**

* Handle an incoming asking.

*

* @param \ Illuminate \ Http \ Request $request

* @param \ Closure $next

* @render mixed

*/

public role handle ( $asking , Closure $next )

{

if ( $request -> route () -> named ( ' profile ' )) {

//

}

render $next ( $asking );

}

Route Groups

Road groups allow you to share route attributes, such as middleware, across a large number of routes without needing to define those attributes on each individual route.

Nested groups attempt to intelligently "merge" attributes with their parent group. Middleware and where conditions are merged while names and prefixes are appended. Namespace delimiters and slashes in URI prefixes are automatically added where appropriate.

Middleware

To assign middleware to all routes within a grouping, you may apply the middleware method before defining the grouping. Middleware are executed in the social club they are listed in the assortment:

                                        

Route :: middleware ([ ' first ' , ' 2nd ' ]) -> group ( role () {

Route :: get ( ' / ' , function () {

// Uses first & second middleware...

});

Route :: get ( ' /user/profile ' , function () {

// Uses first & second middleware...

});

});

Controllers

If a group of routes all utilize the same controller, y'all may utilise the controller method to ascertain the common controller for all of the routes within the group. So, when defining the routes, you lot only need to provide the controller method that they invoke:

                                        

use App\Http\Controllers\ OrderController ;

Route :: controller ( OrderController :: class ) -> grouping ( office () {

Route :: get ( ' /orders/{id} ' , ' evidence ' );

Route :: post ( ' /orders ' , ' store ' );

});

Subdomain Routing

Route groups may also exist used to handle subdomain routing. Subdomains may exist assigned route parameters just like route URIs, assuasive yous to capture a portion of the subdomain for usage in your road or controller. The subdomain may exist specified past calling the domain method earlier defining the group:

                                        

Road :: domain ( ' {account}.example.com ' ) -> grouping ( function () {

Route :: get ( ' user/{id} ' , function ( $account , $id ) {

//

});

});

{notation} In society to ensure your subdomain routes are reachable, you should register subdomain routes before registering root domain routes. This will prevent root domain routes from overwriting subdomain routes which accept the same URI path.

Road Prefixes

The prefix method may be used to prefix each route in the group with a given URI. For example, you may desire to prefix all road URIs within the grouping with admin:

                                        

Road :: prefix ( ' admin ' ) -> group ( function () {

Route :: become ( ' /users ' , part () {

// Matches The "/admin/users" URL

});

});

Route Name Prefixes

The name method may be used to prefix each route proper name in the group with a given string. For example, you may want to prefix all of the grouped road'due south names with admin. The given cord is prefixed to the route name exactly as it is specified, so we will be sure to provide the abaft . grapheme in the prefix:

                                        

Route :: proper name ( ' admin. ' ) -> group ( function () {

Route :: go ( ' /users ' , part () {

// Road assigned name "admin.users"...

}) -> proper noun ( ' users ' );

});

Road Model Binding

When injecting a model ID to a route or controller action, you lot will often query the database to recollect the model that corresponds to that ID. Laravel road model bounden provides a convenient way to automatically inject the model instances directly into your routes. For example, instead of injecting a user's ID, you can inject the entire User model instance that matches the given ID.

Implicit Binding

Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names lucifer a route segment name. For instance:

                                        

utilize App\Models\ User ;

Route :: get ( ' /users/{user} ' , function ( User $user ) {

return $user ->email ;

});

Since the $user variable is blazon-hinted equally the App\Models\User Eloquent model and the variable name matches the {user} URI segment, Laravel volition automatically inject the model instance that has an ID matching the corresponding value from the request URI. If a matching model instance is not establish in the database, a 404 HTTP response volition automatically be generated.

Of course, implicit binding is too possible when using controller methods. Once again, note the {user} URI segment matches the $user variable in the controller which contains an App\Models\User blazon-hint:

                                        

use App\Http\Controllers\ UserController ;

use App\Models\ User ;

// Route definition...

Route :: get ( ' /users/{user} ' , [ UserController :: class , ' show ' ]);

// Controller method definition...

public function show ( User $user )

{

return view ( ' user.profile ' , [ ' user ' => $ user ]);

}

Soft Deleted Models

Typically, implicit model binding volition non call back models that take been soft deleted. Nonetheless, you may instruct the implicit binding to retrieve these models by chaining the withTrashed method onto your route'south definition:

                                        

use App\Models\ User ;

Route :: get ( ' /users/{user} ' , role ( User $user ) {

render $user ->email ;

}) -> withTrashed ();

Customizing The Key

Sometimes you may wish to resolve Eloquent models using a column other than id. To do so, you lot may specify the column in the route parameter definition:

                                        

use App\Models\ Post ;

Route :: go ( ' /posts/{post:slug} ' , function ( Post $post ) {

return $post ;

});

If you would like model binding to e'er utilise a database column other than id when retrieving a given model class, you may override the getRouteKeyName method on the Eloquent model:

                                        

/**

* Go the route key for the model.

*

* @return string

*/

public function getRouteKeyName ()

{

return ' slug ' ;

}

Custom Keys & Scoping

When implicitly binding multiple Eloquent models in a single route definition, you may wish to scope the second Eloquent model such that it must be a child of the previous Eloquent model. For example, consider this route definition that retrieves a weblog post by slug for a specific user:

                                        

use App\Models\ Mail ;

use App\Models\ User ;

Road :: go ( ' /users/{user}/posts/{post:slug} ' , function ( User $user , Mail $mail ) {

return $post ;

});

When using a custom keyed implicit bounden as a nested route parameter, Laravel will automatically telescopic the query to retrieve the nested model by its parent using conventions to estimate the relationship name on the parent. In this case, it volition be causeless that the User model has a relationship named posts (the plural form of the route parameter name) which tin can exist used to retrieve the Post model.

If you wish, you may instruct Laravel to scope "child" bindings even when a custom key is not provided. To practise so, y'all may invoke the scopeBindings method when defining your road:

                                        

utilise App\Models\ Post ;

utilize App\Models\ User ;

Route :: become ( ' /users/{user}/posts/{post} ' , function ( User $user , Postal service $postal service ) {

return $post ;

}) -> scopeBindings ();

Or, yous may instruct an unabridged group of route definitions to use scoped bindings:

                                        

Route :: scopeBindings () -> grouping ( function () {

Route :: become ( ' /users/{user}/posts/{post} ' , function ( User $user , Post $post ) {

return $post ;

});

});

Customizing Missing Model Behavior

Typically, a 404 HTTP response will be generated if an implicitly bound model is not found. However, you may customize this behavior by calling the missing method when defining your road. The missing method accepts a closure that will be invoked if an implicitly bound model can not be found:

                                        

utilize App\Http\Controllers\ LocationsController ;

use Illuminate\Http\ Asking ;

use Illuminate\Support\Facades\ Redirect ;

Route :: get ( ' /locations/{location:slug} ' , [ LocationsController :: class , ' show ' ])

-> name ( ' locations.view ' )

-> missing ( function ( Asking $request ) {

return Redirect :: road ( ' locations.index ' );

});

Implicit Enum Binding

PHP eight.1 introduced support for Enums. To compliment this feature, Laravel allows you lot to blazon-hint a backed Enum on your road definition and Laravel volition merely invoke the route if that route segment corresponds to a valid Enum value. Otherwise, a 404 HTTP response will be returned automatically. For example, given the post-obit Enum:

                                        

<?php

namespace App\Enums;

enum Category : string

{

case Fruits = ' fruits ' ;

case People = ' people ' ;

}

You may define a route that will only be invoked if the {category} route segment is fruits or people. Otherwise, Laravel volition render a 404 HTTP response:

                                        

use App\Enums\ Category ;

apply Illuminate\Support\Facades\ Route ;

Route :: get ( ' /categories/{category} ' , part ( Category $category ) {

return $category ->value ;

});

Explicit Binding

Y'all are not required to use Laravel'southward implicit, convention based model resolution in order to use model bounden. You lot can likewise explicitly define how road parameters stand for to models. To register an explicit binding, employ the router's model method to specify the class for a given parameter. Y'all should define your explicit model bindings at the beginning of the boot method of your RouteServiceProvider class:

                                        

use App\Models\ User ;

utilise Illuminate\Back up\Facades\ Road ;

/**

* Ascertain your route model bindings, pattern filters, etc.

*

* @return void

*/

public function boot ()

{

Road :: model ( ' user ' , User :: form );

// ...

}

Next, define a road that contains a {user} parameter:

                                        

use App\Models\ User ;

Route :: go ( ' /users/{user} ' , function ( User $user ) {

//

});

Since we accept spring all {user} parameters to the App\Models\User model, an instance of that form volition be injected into the route. So, for example, a request to users/ane will inject the User instance from the database which has an ID of ane.

If a matching model instance is not found in the database, a 404 HTTP response will be automatically generated.

Customizing The Resolution Logic

If you wish to define your own model binding resolution logic, you may use the Road::bind method. The closure you pass to the demark method will receive the value of the URI segment and should return the instance of the class that should be injected into the road. Once again, this customization should take place in the boot method of your application's RouteServiceProvider:

                                        

use App\Models\ User ;

use Illuminate\Support\Facades\ Route ;

/**

* Define your route model bindings, pattern filters, etc.

*

* @return void

*/

public function boot ()

{

Route :: bind ( ' user ' , function ( $value ) {

return User :: where ( ' name ' , $value ) -> firstOrFail ();

});

// ...

}

Alternatively, you may override the resolveRouteBinding method on your Eloquent model. This method will receive the value of the URI segment and should render the instance of the class that should be injected into the route:

                                        

/**

* Retrieve the model for a bound value.

*

* @param mixed $value

* @param cord | null $field

* @render \ Illuminate \ Database \ Eloquent \ Model | null

*/

public function resolveRouteBinding ( $value , $field = naught )

{

return $this -> where ( ' name ' , $value ) -> firstOrFail ();

}

If a route is utilizing implicit binding scoping, the resolveChildRouteBinding method will be used to resolve the child bounden of the parent model:

                                        

/**

* Retrieve the child model for a bound value.

*

* @param string $childType

* @param mixed $value

* @param cord | nix $field

* @return \ Illuminate \ Database \ Eloquent \ Model | null

*/

public role resolveChildRouteBinding ( $childType , $value , $field )

{

return parent :: resolveChildRouteBinding ( $childType , $value , $field );

}

Fallback Routes

Using the Route::fallback method, you may define a route that will be executed when no other road matches the incoming request. Typically, unhandled requests will automatically return a "404" page via your application'due south exception handler. However, since you lot would typically define the fallback road within your routes/spider web.php file, all middleware in the spider web middleware group will apply to the route. You lot are free to add additional middleware to this route every bit needed:

                                        

Road :: fallback ( function () {

//

});

{annotation} The fallback road should e'er be the last route registered by your application.

Rate Limiting

Defining Rate Limiters

Laravel includes powerful and customizable rate limiting services that y'all may utilize to restrict the amount of traffic for a given route or group of routes. To get started, you lot should ascertain rate limiter configurations that meet your application'south needs. Typically, this should exist washed within the configureRateLimiting method of your awarding'south App\Providers\RouteServiceProvider class.

Rate limiters are defined using the RateLimiter facade'south for method. The for method accepts a charge per unit limiter proper noun and a closure that returns the limit configuration that should utilize to routes that are assigned to the charge per unit limiter. Limit configuration are instances of the Illuminate\Cache\RateLimiting\Limit class. This class contains helpful "builder" methods so that you tin quickly define your limit. The rate limiter name may be whatever string yous wish:

                                        

utilise Illuminate\Cache\RateLimiting\ Limit ;

use Illuminate\Support\Facades\ RateLimiter ;

/**

* Configure the rate limiters for the application.

*

* @return void

*/

protected role configureRateLimiting ()

{

RateLimiter :: for ( ' global ' , function ( Request $request ) {

return Limit :: perMinute ( chiliad );

});

}

If the incoming request exceeds the specified charge per unit limit, a response with a 429 HTTP status lawmaking will automatically be returned by Laravel. If you would similar to define your own response that should exist returned by a rate limit, you may utilize the response method:

                                        

RateLimiter :: for ( ' global ' , function ( Request $asking ) {

return Limit :: perMinute ( chiliad ) -> response ( function () {

return response ( ' Custom response... ' , 429 );

});

});

Since rate limiter callbacks receive the incoming HTTP asking instance, you may build the advisable charge per unit limit dynamically based on the incoming request or authenticated user:

                                        

RateLimiter :: for ( ' uploads ' , function ( Request $request ) {

render $request -> user () -> vipCustomer ()

? Limit :: none ()

: Limit :: perMinute ( 100 );

});

Segmenting Rate Limits

Sometimes you may wish to segment rate limits past some arbitrary value. For example, you may wish to let users to admission a given route 100 times per minute per IP accost. To reach this, yous may employ the by method when building your rate limit:

                                        

RateLimiter :: for ( ' uploads ' , function ( Request $asking ) {

return $request -> user () -> vipCustomer ()

? Limit :: none ()

: Limit :: perMinute ( 100 ) -> past ( $asking -> ip ());

});

To illustrate this feature using another example, we can limit admission to the route to 100 times per minute per authenticated user ID or 10 times per minute per IP address for guests:

                                        

RateLimiter :: for ( ' uploads ' , function ( Request $request ) {

return $asking -> user ()

? Limit :: perMinute ( 100 ) -> by ( $request -> user () ->id )

: Limit :: perMinute ( x ) -> by ( $asking -> ip ());

});

Multiple Rate Limits

If needed, yous may render an assortment of charge per unit limits for a given charge per unit limiter configuration. Each rate limit will be evaluated for the route based on the order they are placed within the array:

                                        

RateLimiter :: for ( ' login ' , function ( Request $request ) {

return [

Limit :: perMinute ( 500 ),

Limit :: perMinute ( 3 ) -> by ( $request -> input ( ' e-mail ' )),

];

});

Attaching Rate Limiters To Routes

Rate limiters may be attached to routes or route groups using the throttle middleware. The throttle middleware accepts the name of the rate limiter you wish to assign to the road:

                                        

Route :: middleware ([ ' throttle:uploads ' ]) -> grouping ( function () {

Route :: post ( ' /sound ' , function () {

//

});

Route :: postal service ( ' /video ' , function () {

//

});

});

Throttling With Redis

Typically, the throttle middleware is mapped to the Illuminate\Routing\Middleware\ThrottleRequests class. This mapping is defined in your application's HTTP kernel (App\Http\Kernel). However, if yous are using Redis as your application's enshroud driver, you may wish to change this mapping to use the Illuminate\Routing\Middleware\ThrottleRequestsWithRedis class. This class is more efficient at managing charge per unit limiting using Redis:

                                        

' throttle ' => \Illuminate\Routing\Middleware\ ThrottleRequestsWithRedis :: course ,

Form Method Spoofing

HTML forms do not support PUT, PATCH, or DELETE actions. And so, when defining PUT, PATCH, or DELETE routes that are called from an HTML class, you volition need to add a hidden _method field to the class. The value sent with the _method field will exist used as the HTTP request method:

                                        

< form action = " /instance " method = " Postal service " >

< input type = " hidden " name = " _method " value = " PUT " >

< input type = " subconscious " proper name = " _token " value = " {{ csrf_token() }} " >

< / grade >

For convenience, you may use the @method Blade directive to generate the _method input field:

                                        

< form activity = " /example " method = " POST " >

@ method ( ' PUT ' )

@ csrf

< / course >

Accessing The Electric current Route

You may use the electric current, currentRouteName, and currentRouteAction methods on the Route facade to admission information about the route treatment the incoming request:

                                        

apply Illuminate\Support\Facades\ Route ;

$route = Route :: electric current (); // Illuminate\Routing\Road

$name = Route :: currentRouteName (); // string

$action = Road :: currentRouteAction (); // string

You may refer to the API documentation for both the underlying class of the Road facade and Route instance to review all of the methods that are available on the router and route classes.

Cross-Origin Resources Sharing (CORS)

Laravel can automatically respond to CORS OPTIONS HTTP requests with values that yous configure. All CORS settings may be configured in your application's config/cors.php configuration file. The OPTIONS requests will automatically be handled by the HandleCors middleware that is included by default in your global middleware stack. Your global middleware stack is located in your awarding'south HTTP kernel (App\Http\Kernel).

{tip} For more than information on CORS and CORS headers, please consult the MDN web documentation on CORS.

Route Caching

When deploying your application to product, you should take reward of Laravel's route cache. Using the road cache will drastically decrease the corporeality of time it takes to register all of your awarding's routes. To generate a route cache, execute the road:enshroud Artisan command:

                                        

php artisan route:cache

After running this control, your cached routes file will be loaded on every request. Call up, if you add whatsoever new routes you will need to generate a fresh route enshroud. Because of this, y'all should only run the route:cache command during your projection's deployment.

You may use the route:clear command to clear the road enshroud:

                                        

php artisan route:clear

How Do I Pass Route-id-name To Controller,

Source: https://laravel.com/docs/9.x/routing

Posted by: courtexcirs.blogspot.com

0 Response to "How Do I Pass Route-id-name To Controller"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel