What is Laravel basic routing - view routes?
What is Laravel?
Laravel is a PHP framework with expressive and elegant syntax that is used to create web applications.
Like other frameworks, it has a router, a component that expressively channels
Every
Routing in Laravel
In Laravel, the router component is located at the root folder. This folder is named routes, and comes with four major files by default:
channels.phpapi.phpconsole.phpweb.php
Basic routing
For basic routing, you would only work with the web.php file. By default, it comes with the code below.
Code
This code returns a welcome page when the default page is visited, such as: www.example.com/.
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Explanation
From the code above, we can observe the Route:: syntax.
This Route syntax is a Laravel facade that makes routing possible and is imported into the web.php.
Route operations
When we perform a Route operation, we need to handle the various request methods sent to the route.
These methods include
GET, POST, PUT, PATCH, and DELETE.
From the code above, we notice the use of the get method followed by a parenthesis, and then single quotes.
What you use in between the single quotes is what will be typed into URI.
Example
Let’s say you want visitors to visit your “About Us” page, but you don’t want them to input the /about us in URI.
A short-form link says
/au, short for “about us”.
You can use the /au in between the single quotes.
After the URI, a callback function is used to return the views or parse the request to a Controller to handle the request further.
use Illuminate\Support\Facades\Route;
Route::get('/home', function () {
return view('home');
});
Explanation
You will notice from the code above that the URI is /home, which means that we are requesting the home view.
The view('home') does not have a .php extension because Laravel has a templating engine called Blade.
Blade is a templating engine Laravel uses to serve pages expressively and elegantly.
It comes with a boilerplate that simplifies the whole page display on the browser and has a .blade.php extension.
The
home.blade.phpfile is located at:resources => views =>
home.blade.php
You can now add your
Summary
Basic routing involves handling a $uri with a $callback function. You either pass to a Controller or display a particular resource or page through various HTTP request methods, as seen below.
Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);