How to Create Route in Laravel 10?

Last updated on October 4, 2023

In the Laravel, routes are used to define the URLs for the web application. When a user makes a request to the application, Laravel’s routing system determines which route matches the request and then calls the corresponding controller. The Laravel framework keeps the route files in the routes directory.

In Laravel, we create web routes in web.php from the routes directory and API routes in the api.php from the routes directory.

There are different route methods in Laravel,

get($path, $callback);
post($path, $callback);
put($path, $callback);
delete($path, $callback);
patch($path, $callback);
options($path, $callback);

Creating web routes is quite simple. In this article, we will learn to create a route with two examples.

Create a Web Route with a Closure:

To create a web route in the Laravel framework, open the web.php from the routes directory and add the below code.

Route::get('/contact-us', function () {
   return view('contact');
});

In the above example of code, we simply create a web route through the get() method which means Laravel will be accepting HTTP GET requests for this route. The first argument /contact-us is the URL slug for the route. It specifies the URL at which this route will respond to incoming requests. The second argument is a closure function. It will be executed when a user accesses the /contact-us URL with a GET request.

This route will load the contact.blade.php from the views directory when we open our Laravel application in the browser along with /contact-us.

Example URL: https://yourdomain.com/contact-us

Create a Route with Controller:

In this example, we will create a web route with the URI /contact-us for handling HTTP GET requests. This route will be handled by the ContactUsController and its show() method.

Route::get('/contact-us', 'ContactUsController@show');

In this example, we have defined a route that is associated with the show() method within the ContactUsController controller. When a user comes on the route Laravel will call the show() method from ContactUsController.

Conclusion:

In this article, we explained how can we create web routes in Laravel along with examples.


Written by
I am a web developer with over 2 years of industry experience, specializing in PHP, JavaScript, MySQLi, and Laravel. I create dynamic and user-friendly web applications, committed to delivering high-quality digital solutions.

Share on:

Related Posts

Improved by: Ayaz Ali Shah

Tags: Laravel,