👨‍💻

#04 Laravel Overview & Setup (Routing & Middleware basics)

2024/07/25に公開

Introduction

PHP is a kind of old web development language which released in 1995. But it has a variety of frameworks for web development and it is still a popular language in the real world. This time, the most famous PHP full-stack framework will be introduced. Laravel.

So, what is Laravel?

Laravel is a web application framework with expressive, elegant syntax. A web framework provides a structure and starting point for creating your application, allowing you to focus on creating something amazing while we sweat the details.

There are many reasons why Laravel is so popular, you check the official document or do some research, but trying to use it will be easier and faster.

Requirement

Make sure your machine has installed those things marked below.

  • WSL2
  • Docker

Installation (Windows)

Open Windows Terminal and begin a WSL2 terminal session, run the following command to create a new Laravel project with a directory named laravel-app

curl -s https://laravel.build/laravel-app | bash

And now you can have a cup of tea as the installation may take several minutes.

When it is done, go to the project directory and start Laravel Sail

./vendor/bin/sail up

According to the official document,

Laravel Sail provides a simple command-line interface for interacting with Laravel's default Docker configuration

Which has done everything for you, the thing you need to do is focus on development.

VSCode development environment Setup

Duelling with different projects with their language versions, every extension in VSCode shows your code is wrong. painful. But we can get the advantages of remote development via Docker and VSCode.

So now, the Laravel project is already containerized and we can set up VSCode for development.

  1. Install Remote Development in VSCode
  2. Update docker-compose file by adding tty:true to your service(s)
  3. build and run your project with docker-compose
  4. Open a remote window in VSCode
  5. select Attach to Running Container and select the right container
  6. open the project root folder that wrote on the docker-compose file

Now your project should look fine and no strange error comes out.

The advantage is you can install the needed extensions to the container without affecting your local machine. Make your extension list clean.

Frontend (Inertia&vue)

You can develop frontend with Blade or traditional PHP. But for this time, Vue.js will be used for frontend development. To make use of the Laravel framework, Inertia will be installed and used as a bridge between Laravel and Vue.js via the starter kit "Breeze" developed by the official. So, what is Breeze?

Laravel Breeze is a minimal, simple implementation of all of Laravel's authentication features, including login, registration, password reset, email verification, and password confirmation. In addition, Breeze includes a simple "profile" page where the user may update their name, email address, and password.

described by the official document.

Let's install Breeze to our project by the following command.

composer require laravel/breeze --dev

Next, install Breeze's scaffolding with Vue.

php artisan breeze:install vue

php artisan migrate
npm install

*Breeze also provides React scaffolding, so you can choose either one.

Basics

Routing

Laravel routes accept simple route declaration with URI and a function closure as below.

use Illuminate\Support\Facades\Route;

Route::get('/foo', function () {
   return 'Hello world';
});

All the routes should be defined in the routes directory and the route files are automatically loaded by RouteServiceProvider :

public function boot(): void
    {
        $this->routes(function () {
            Route::middleware('api')
                ->prefix('api')
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->group(base_path('routes/web.php'));
        });
    }

The web.php is for web interface and api.php is for API in default. Both routes are assigned to their own middleware which provides their own features. For example, session state is provided in web middleware. In the above sample code, /api URI is applied to every route in the api group by prefix('api') .

Although we can simply define routes and handle the logic in the routes' files, but while the project is extended, it will become hard to manage. Laravel provides an alternative way to define routes with the controller's closure:

Route::get('/foo', [FooBarController::class, 'bar']);

There are many route options to modify but let's focus on other basics first. If you want more detail about route, check out the link here.

Middleware

if you want every HTTP request to apply certain middleware, list the class in the Kernel.php as below.

//...
protected $middleware = [
        \App\Http\Middleware\TrustProxies::class,
        \Illuminate\Http\Middleware\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        //add here...
    ];

Middleware can also be applied to a route or group like the api and web does.

Route::get('/home', function () {
    // ...
})->middleware(CustomMiddleware::class);

//or

->middleware([First::class, Second::class]);

For convenience, you can name your middleware class and assign it by name/alias.

protected $middlewareAliases = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    //...
];

// usage

Route::get('/home', function () {
    // ...
})->middleware('auth');

There are more detail and features are provided, go to the official site for more information.


I think that is all for this post, and we will talk more about Laravel basics later on.

Reference

Official site: https://laravel.com/

Discussion