Learning to master Laravel Routes
If we look at the backend, eventually we come across routes. This is the foundation of the backend because every request the server receives is sent to a controller through the routing list. This relies on the controller or action.
Backend Routing and Cross-Site Scripting in Laravel
On servers, there are the private and public routes. Public routes could pose an opportunity for XSS.
The issue arises due to the fact that a user could be taken from a location that does not require an account token, but instead go to one which does and gain access with no token.
The best way to resolve the problem is to use an entirely brand new HTTP header, and include "referrer" within the URL in order to avoid this situation.
'main' => [ 'path' => '/main', 'referrer' => 'required,refresh-empty', 'target' => Controller\DashboardController::class . '::mainAction' ]
Basic Routing for Laravel
In Laravel the routes are built in the web.php and api.php files, and Laravel has two routes available in default. One for the WEB as well as one that is intended for API. API.
These routes reside in the routes/ folder, but they are loaded in the Providers/RouteServiceProvider.php
Instead of doing this we can load the routes directly inside the RouteServiceProvider.php skipping the routes/ folder altogether.
Redirects
// Simple redirect Route::redirect("/class", "/myClass"); // Redirect with custom status Route::redirect("/home", "/office", 305); // Route redirect with 301 status code Route::permanentRedirect("/home", "office");
In the redirect route it is not permitted to make use of the "destination" and "status" keyword to define parameters since they are protected by Laravel.
// Illegal to use Route::redirect("/home", "/office/status");
Views
The Views files are . blade.php files that serve as the frontend for our Laravel application. Blade is a templating engine. This is the most common method to build a full stack app using Laravel.
If our route is to provide a view, you can use the view method in the Route facade. It can accept a route parameter as well as a view's name as well as an array of values to be passed to the view.
// When the user will enter the 'my-domain.com/homepage // the homepage.blade.php file will be rendered Route::view("/homepage", "homepage"); // Let's assume our view wants to say "Hello, name", // by passing an optional array with that parameter // we can do just that and if the parameter is missing but // it is required in the view, the request will fail and throw an error Route::view('/homepage', 'homepage', ['name' => ""]);
Route Liste
If the application expands in size, so does the amount of requests that must be directed. And with a great volume of data , comes plenty of confusion.
This is where the art route:list can help. It offers a summary of all the routes defined by the application as well as their middlewares and controllers.
php artisan route:list
The program will provide an overview of the possible routes, without middlewares. For this, we have to utilize the flag with the '-v'
php artisan route:list -v
In the event that you might be using Domain Driven Design and your routes might have certain names, you could employ the filters offered by this option.
php artisan route:list -path=api/account
This will only show the routes beginning by using API/Account. Account/API..
On the other hand you are able to tell Laravel to not include or exclude the third party defined routes with options such as that of -except-vendor or -only-vendor selections.
Route Parameters
Sometimes we will have to capture certain parts of the URI through the route, such as an ID for a user or token. It is possible to do this by creating a parameter for the route, which is always encased inside the ' ' braces and must only include letters.
If our routes contain dependencies within the callbacks, the Laravel Service Container will automatically add them.
use Illuminate\Http\Request; use Controllers/DashboardController; Route::post('/dashboard/id, function (Request $request, string $id) return 'User:' . $id; Route::get('/dashboard/id, DashboardController.php);
Mandatory Parameters
The parameters that are required to be met by the caller are the ones that we aren't allowed to circumvent when making attempts to dial. If we try, an mistake could be reported.
Route::post("/gdpr/userId", GetGdprDataController.php");
Now inside the GetGdprDataController.php we will have direct access to the $userId parameter.
the public function __invoke(int userId) // Use the userID we have received...
The route can include any number of parameters and they can be added to callbacks for routes / controllers according to the order in which they are entered:
Do you want to know what we did to increase the number of visitors to our website by 1,000 per cent?
Join the 20,000+ subscribers to our weekly newsletter with insider WordPress tricks!
// api.php Route::post('/gdpr/userId/userName/userAge', GetGdprDataController.php); // GetGdprDataController.php public function __invoke(int $userId, string $userName, int $userAge) // Use the parameters...
Optional Parameters
In the event that you want to implement an action within a particular method only when a parameter is present and not affect the application in general or the whole application, we can make an additional parameter.
This is indicated by the letters '?' added to them.
Route::get('/user>' (function (int age = null) *if (!$age) Log::info("User doesn't have the age of"); else Log::info("User's Age is " . $age); Route::get('/user/"; method (int"$name" is "John Doe") Log::info("John Doe")Log::info("User's name begins with " . $name);
Route Wildcard
"Where Method "where method" will accept the name of the parameter, as well as the regex rule which is employed to confirm the parameters. It defaults to accepting the first parameter, but when we're faced with a variety of options, it is possible to provide an array with the names of each parameter as keys, as well as the rule's value. Laravel will sort them out for us.
Route::get('/user/age', function (int $age) // ->where('age', '[0-9]+'); Route::get('/user/age', function (int $age) // ->where('[0-9]+'); Route::get('/user/age/name', function (int $age, string $name) // ->where(['age' => '[0-9]+', 'name' => '[a-z][A-z]+');
We can take this a step further and apply to all routes in our application with the use of the pattern method to the Route facade
Route::pattern('id', '[0-9]+');
It will cause each ID parameter to be validated by this regex expression. After we've defined the expression, it will be instantly applied to any possible routes that have that name.
Route::get('/find/query', function ($query) // )->where('query', , '. *');
Named Routes
What is the best way to create name-brand Routes
An easy way to accomplish this is through the name method that is chained to the Route facade. Names should be distinct.
Route: get ('/', function () )->name("homepage");
Route Groups
Route groups allow you to connect middleware and other route characteristics across a range of routes without needing to define it for each and every route.
Middleware
In order to assign a middleware any of the methods, we must include the middlewares in a group before by using the group method. Another factor to be considered is the fact that middlewares will be performed in the same manner when they are included in the group.
Route:middleware(['AuthMiddleware', 'SessionMiddleware'])->group(function () Route::get('/', function() ); Route::post('/upload-picture', function () ); );
Controllers
In the event that a group is using the same controller, it is possible to utilize the controller method to determine the controller that is common to each routes within that group. Now we have to specify which method each route will utilize to contact.
Route::controller(UserController::class)->group(function () Route::get('/orders/userId', 'getOrders'); Route::post('/order/id', 'postOrder'); );
Subdomain Routing
The routes can be utilized to subdomain-specific routing. The domain could be captured and a portion of the subdomain to be used for our controller as well as routes. Utilizing the domain method on the Route facade, we can identify the routes that we utilize in a domain
Route::domain('store.enterprise.com')->group(function() Route::get('order/id', function (Account $account, string $id) // Your Code );
Name Prefixes and Prefixes
If we are faced with a set of routes, instead of switching them all in one go it is possible to make use of the utils provided by Laravel includes, like the name and prefix that appears on the Route façade.
Methods for prefixing can be used to prefix all routes within the group by the given URI as well as using the name method, which can be employed to prefix each route's name with a certain amount of characters.
It allows us to design similar routes to Admin without the need to change each name and prefix to differentiate them.
Route::name('admin. ")->group(function() Route::prefix("admin")->group(function() Route::get('/get')->name('get'); Route::put('/put')->name(put'); Route::post('/post')->name('post'); ); );
In the future, the URI for the routes is going to include admin/get as well as admin/put. as well as the names admin.get, admin.put, admin.post.
Route Caching
What is Route Caching?
The caching of routes will reduce the time required to record every application's routes.
Running php artisan route:cache an instance of Illuminate/Routing/RouteCollection is generated and after being encoded, the serialized output is written to bootstrap/cache.routes.php.
It's crucial to utilize Route Caching
By not using the feature of route cache which Laravel offers it, we're slowing our website faster than is necessary as well as reducing user retention and general enjoyment of the site.
Based on the size of your project as well as the quantity of routes. In the case of just one command, it can accelerate your app by 1.3x times or up to 5x times.
Summary
Routing is at the heart of Backend development. Laravel excels at this through its lucid way of organizing and delineating routes.
- Simple setup and administration in My dashboard. My dashboard
- Support is always available.
- The most efficient Google Cloud Platform hardware and network, that is driven by Kubernetes for maximum scalability
- Enterprise-level Cloudflare integration to improve performance and security.
- A global audience can be reached with up to 35 data centers, as in addition to more than 275 PoPs in all over the all over the world.
This post was posted on here