Icon
Get In Touch
#laravel

Understanding Routing in Laravel

Laravel Routing Basics

What is Routing?

Routing is like giving your application a map. It defines how your app responds to URLs that users visit. Each route is associated with a function or controller, which handles the request and decides what to show the user.

How to Create a Basic Route

Start by creating a route in the routes/web.php file:

1
Route::get('/greeting', function () {
2
return 'Hello, welcome to my website!';
3
});

Route::get('/greeting', ...): This means that when someone visits the URL /greeting, Laravel will call the function inside the route and return the message "Hello, welcome to my website!".

Available Router Methods

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

1
Route::get($uri, $callback);
2
Route::post($uri, $callback);
3
Route::put($uri, $callback);
4
Route::patch($uri, $callback);
5
Route::delete($uri, $callback);
6
Route::options($uri, $callback);

GET is used to request data from a specified resource.
POST is used to send data to a server to create a resource.
PUT is used to send data to a server to update a resource.
PATCH is used to apply partial modifications to a resource.
DELETE is used to delete the specified resource.
OPTIONS is used to describe the communication options for the target resource

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 so that you do not have to define a full route or controller for performing a simple redirect:

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

View Routes

If your route only needs to return a view, you may use the Route::view method. The view method accepts a URI as its first argument and a view name as its second argument. In Laravel, views are stored in the resources/views directory. Views are typically written in Blade, but you can also write plain HTML if needed.

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

©2024 Codeblockz

Privacy Policy