Laravel Route Parameters

Laravel Route Parameters

Required Parameters:

We need to capture segments of the URI within our route.

We are going to see how to pass parameters through two or many views inside the closure function.

Route::get('/home', function () {
    return "Hello Home Page,
Welcome to Laravel Project";
});

Route::get('/about', function () {
    return "Hello About Page, I am
Laravel";
});

Route::get('/contact', function () {
    return "Hello Contact Page, Call
Me";
});

Output:

Laravel Route Parameters 1
Laravel Route Parameters 2
Laravel Route Parameters 3

We need to capture a user`s id from the URL.

We do so by defining route parameters.

Route::get(‘/user/{id}’,function($id)
{ 
Return ‘user ‘ , $id;
}); 

E.g.:

Route::get('/video/{id}', function($id) {
return "Here We Can Find
Video No. ". $id;
});

Output:

Laravel Route Parameters 4

In the above example, we can see how to pass the variable to the closure function.

We define as many route parameters as required by our route:

Route::get(‘posts/{post}/comment}’,function( $postId, $commentId)
{
//
});

E.g.:

Route::get('/image/{id}/{name}', function($id, $name) {
return "Hii This Is Image No. ". $id . " " . $name;
});

Output:

Laravel Route Parameters 5

In the above example, the 50 is represented as an ( id ), the Rafia describes as a ( name ).

Route parameters are always enclosed within { } braces, and it should consist of any alphabetic characters. It may not contain a – character. Instead of using the – character, we use an underscore (_). Route parameters are placed into route callbacks/controllers based on their order – the names of the callback/controller arguments do not matter.

Optional Parameters

We need to specify route parameters occasionally, but we make the presence of route parameter route. We can place a (?) mark after the parameter name.

We make sure to give the route`s corresponding variable a default value.

Route::get(‘user/{name?},’function ($name = null)
{
Return $name;
});
Route::get(‘user/{name?},’ function ($name = ‘John’)
{
Return $name;
}) 

Regular Expression Constraints

We may constrain the format of our route parameters using the where method.

Route::get(‘user/{name}’,function ($name)
{
//
}) -> where(‘name’, ‘[A-Za-z]+’);
  
Route::get(‘user/{id}’, function ($id)
{
//
}) -> where(‘id’, ‘[0-9]+’);
  
Route::get(‘user/{id}/{name}’,  ($id, $name)
{
//
}) -> where([‘id’ => ‘[0-9]+’, ‘name’ => ‘[a-z]’]); 

The where method obtain the name of the parameters and a regular expression defining the parameter that should be constrained:

Global Constraints

We would like a route parameter to always be constrained by a given regular expression, we can use the pattern method. We can define these patterns in the boot method of ours RouteServiceMethod.

public function boot()
{
Route::pattern(‘id’,  ‘[0-9]+’); 
Parent::both(); 
}

Once the pattern has been defined, it will be automatically applied to all the outers using the parameter name:

Route::get(‘user/{id},’  function($id)
{
//
});

Encoded Forward Slashes

The Laravel routing component allows all the characters except /. We must explicitly allow / to be part of our placeholder using a where condition regular expression.

Route::get(‘search/{search}’,  function ($search)
{
Return $search;
}) -> where(‘search’,  ‘.*’);  

Related Topics

Laravel Eloquent Database Relationships

Eloquent Relationships Laravel: Database tables are related to one another. Eloquent manages and work with easy relationships. It supports some different types of relationship, which are as follows: One to oneOne to manyMany...

8 minutes read.

Laravel Controller Middleware

Controller Middleware Middleware can be assigned to the controller`s routes in our route files: Route::get(‘profile’, ‘UserController@show’) ->middleware(‘auth’); It is more convenient to specify middleware within our controller`s constructor. Using the middleware method from our controller`s constructor,...

1 minute read.

Laravel Forms

CSRF Field For defining an HTML form in our application, we should include a hidden CSRF token field in the form, so that the CSRF protection middleware can validate the request. We use the...

3 minutes read.

Laravel Templating Inheritance

Introduction: The Blade is a PHP Templating Engine. It grabs the PHP code and makes it easy for us to implement in HTML. The Blade is a simple, and powerful Templating Engine provided by...

4 minutes read.

Laravel Control Statements

Blade also provides convenient shortcuts for common control structure in PHP, such as conditional statements and loops. These shortcuts provide a very clean working with PHP structures, while also remain familiar to...

3 minutes read.

Database Migrations

Database Migrations in Laravel Introduction Migrations are version control for our database. It allows our team to modify and share the application`s database. Migrations are paired with schema builder to build an application`s database...

2 minutes read.

Laravel Basic Controllers

Controllers group relate request handling logic into a single class. They are stored in the app/Http/Controllers directory. Basic Controllers Defining Controllers: The controllers extend the base controller class included with Laravel. The base class...

2 minutes read.

Laravel vs Other Frameworks

Laravel is one of the top listing PHP framework. Some of the reasons which make Laravel top listing PHP framework that are as follows: Authorization Technique.Object-Oriented Libraries.Artisan.MVC Support.Security.Database Migration.Database Template Engine. In this Pie Chart distribution, we...

6 minutes read.

Laravel Authentication

Authentication is a process of identifying user credentials. Laravel makes implementing authentication very simple. The authentication configuration file is located at config/auth.php that contains various documented options for adjusting the behavior of the authentication...

4 minutes read.

Laravel Named Routes

Named Routes Named routes allow the suitable generation of URLs or redirects to specific routes. We specify a name for a route by changing the name method onto the route definition: Syntax:  Route::get(‘user/profile’, function () {...

2 minutes read.

Laravel Route Parameters

Required Parameters: We need to capture segments of the URI within our route. We are going to see how to pass parameters through two or many views inside the closure function. Route::get('/home',...

2 minutes read.

Laravel First Packages

First Packages  Laravel provides the following ready to use packages: Cashier: It was introduced in Laravel 4.2 version, it provides an interface for managing subscription billing service, like handling coupons and generating invoices. SSH: It was...

2 minutes read.

Laravel Basic Routing

Basic Routing The basic Laravel routes accept a URI and a Closure, providing a straightforward method for defining routes: Route::get('/', function () { return view('welcome') }); E.g.: Route::get('/', function () { return "Hello Laravel"; }); Output: We...

3 minutes read.

Laravel Data Views

Passing the Data Views The data should be an array with the key/value pairs while passing the information in the following (return view(‘greeting’, [‘name’ => ‘John’]);) manner. Inside the view, we...

4 minutes read.

Laravel Creating Views

Creating Views Views hold the HTML served by our application, and it separates our controller/application logic with the help of presentation logic. Views are stored inside the resources/views directory. A simple view...

2 minutes read.

Laravel Resource Controllers

Laravel resource routing assigns the “CRUD” routes to a controller with the help of single line code. For E.g., If we wish to create a controller that handles all HTTP requests “photos” stored by...

4 minutes read.

Laravel Tutorial

Laravel Tutorial is a PHP based web-framework; it is used for developing high-end web applications by using significant syntax's. It has a substantial collection of tools and provides application architecture....

5 minutes read.

Laravel Displaying Data

Display data that is passed to our Blade views by enclosing the variable in curly braces. The following route is given below: Route::get('greeting', function () { return view('welcome', ['name' => 'rafia']); }); We display...

2 minutes read.

Laravel Uploading Files

Retrieving Uploaded Files We can access files from an Illuminate\Http\Request. By using the file method or using the dynamic properties. The file method returns an instance of the Illuminate\Http\UploadedFile class that extends the...

2 minutes read.

XAMPP Installation

install xampp on windows XAMPP is a free & open-source stack package which is developed by Apache, mainly it consists of Apache HTTP server, Maria DB database for scripts written in the...

2 minutes read.