PHP Laravel Framework Routing URL with Tips and Tricks
In this article, you’ll get familiar with creating URL routings in Laravel and also some advance concepts of routing which include redirection, CSRF verification, and authorization.
What is URL routing in web applications?
URL Routing is a term used for a web application. By specifying URL client will be returned with data in the form of an HTML web page or a JSON response. In advance, the MVC framework makes heavy use of routing because of many benefits such as SEO optimization of URL, hiding application structure, dynamically sending a response to the client based on URL and parameters, 301 redirection and many more.
For example: If clients requests for uses list to page through URL https://www.example.com/users than the response will be a page with a list of users and if client request for user details page whose URLs is https://www.example.com/user/15/show will return page which contains information related to a particular requested user.
Here users and user/15/show are called routes. Such kind of method of handling and responding with data based on clients request URL is difficult or not feasible in core PHP(I’m not saying that is it impossible).
Getting started with Laravel URL Routing
In Laravel, all application routes must be defined in routes/web.php
. Use class Route
followed by state method which specifies the method type such as GET, POST, PUT, PATCH and DELETE.
Below is a simple route which returns text when you got to URL http://www.127.0.0.1/laravel-project/simple-route
of your project.
Route::get('simple-route', function () { return 'Welcome to Laravel Routes'; });
Passing view to route
of course, the above example is very straight forward and easy. For a real-life example, a given URL must return data or a web page. So create a PHP web page create_form.blade.php
which contains HTML in the path laravel-project/resources/views/product/create_form.blade.php
.
To return display create_form
use view()
function which takes a relative path to create_form
page.
Route::get('product/create', function () { return view('product.create_form'); });
The dot.
after the product is represented as a path. You can also pass data into the second argument of view()
function.
Passing the callback method to route
In Laravel, Controller is having the responsibility of handling business logic of entire application. When a client request for URL a controller method is passed as callback function of that particular route. Through this, the callback function is triggered which returns a web page or JSON data as a response.
Route::get('product/create', 'ProductController@createForm');
Here ProductController
is a controller and method createForm
is a callback function.
In laravel-project/app/Http/Controllers/ProductController.php
.
class ProductController extends Controller { public function createForm(Request $request){ $additional_data_to_view = []; return view('product.create_form', $additional_data_to_view); } }
Extra Positional Parameters for Route
There is also an option for passing dynamically values into the route. All these dynamical route parameters must be given a name and enclosed inside curly braces such as {product_id}
.
In routes web.php
.
Route::get('product/edit/{product_id}', 'ProductController@editForm');
In laravel-project/app/Http/Controllers/ProductController.php
.
public function createForm(Request $request, $product_id){ $additional_data_to_view = []; return view('product.create_form', $additional_data_to_view); }
These positional arguments can be retrieved from the controller method. The $request
is an object which contains the information related to the current request and $product_id
is a positional parameter.
Note
The positional argument position and name must be same as specified in routes else you’ll receive 404 No found error.
You can specify has many numbers of positional parameters you can. But while calling you to need to make sure that you have passed all parameters in the same order as you specified.
And for optional positional parameter mark them with ?
shown below.
//For multiple parameters Route::get('product/edit/{product_id}/category/{category_id}', 'ProductController@editForm'); //For optional parameters Route::get('product/edit/{product_id?}/category/{category_id?}', 'ProductController@editForm');

Udemy Laravel Course for Beginners
Using Named Routes
Routes can also be identified by a name through chaining name()
method. It takes string route name as parameter.
Through this URL generation for routing is made easier as a change or modification in route will not affect that route which is called through named route.
Route::get('product/edit/{product_id}', 'ProductController@editForm')->name('product-edit');
You can redirect to the above route using its name shown below.
return redirect(route('product-edit', ['product_id' => 1 ])); // with named routes return redirect('product/edit/1'); // without named routes
Advantages of using Named Routes over Normal Routes
- Issue of modification of URLs can be addressed.
- Easy and convenient rather than using URLs for redirection.
Redirecting Routes
You can use a function redirect()
which takes route URL for redirection of other parts of the application.
return redirect('product/edit/1');
You can also use Route::redirect
method for redirecting one route to another.
Route::redirect('/from-this-route-url', '/to-this-route-url');
Redirecting with session flash message.
If you want to display a flash message to the client after redirection you can use with()
method which takes the first parameter as key and second parameter as a message to show.
return redirect('product/edit/1')->with('any_session_key', 'message'); return redirect('product/edit/1')->with('success', 'Product created successfully.');
Alternatively, you can also use $request->session()->flash('any_session_key', 'message')
for showing a flash message to the client.
For retrieving flash messages in views.
Session::get('any_session_key');
Grouping of Routes
For grouping similar routes and avoid clutter use Route::group
method which takes an array as an argument. This argument array contains an index prefix
which is the entry inside the route.
Route::group(['prefix' => 'product/'], function () { Route::get('list', 'ProductController@listData'); Route::get('create', 'ProductController@create'); Route::post('store', 'ProductController@store'); });
Suppose if you navigate to URL of your application http://www.127.0.0.1/laravel-project/product/list
will trigger listData
method and similarly http://www.127.0.0.1/laravel-project/product/create
trigger create
method of ProductController
.
You can also create a nested route which looks like below.
Route::group(['prefix' => 'prefix-word-one'], function () { // .... // Some routes here // .... Route::group(['prefix' => 'prefix-word-two'], function () { // .... // Some routes here // .... }); });
Middleware in Routing
Middleware is those classes which stay in between application incoming request and outgoing request. They are used for authentication, redirection is the user does not have enough permission to access a web page and many more.
The index middleware
is specified inside Route::group
method. You can also chain multiple middlewares together for a particular route or for a group of routes.
Route::group(['middleware' => ['middleware1', 'middleware2']], function () { // Some routes here });
For specifying middleware to a particular route.
Route::get('product/edit/{product_id}', 'ProductController@editForm')->middleware('check_if_logged_in', 'check_if_authorized');
You can have one and many middlewares as you need.
Model Route Binding
Model route binding mechanism provides fast and convenient ways of fetching object of positional route parameter from the database.
It is just like selecting an object by route parameter.
// In web.php Route::get('product/edit/{product_id}', 'ProductController@editForm'); // In ProductController public function editForm(ProductModel $product_id){ //... }
We are binding route parameter product_id
to ProductModel by using ProductModel $product_id
as a parameter in editForm
method.
ProductModel $product_id
will perform where query on ProductModel
and retrieves object.
If you want to customize the binding process then you can visit the laravel model route binding page.
Conclusion
You can come to an end of our article on PHP Laravel Routing URL with Tips and Tricks. For any queries, you can comment below and our developer will address your issue and also don’t forget to share.
Related Posts
- Laravel Sending Emails | The Easiest and Simple Way
- Laravel Emails | Sending emails with multiple attachments
- How to Send Email Using Laravel with Mailable Markdown Class
- PHP sending email using mail() function