Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Using Laravel - Comprehensive Tutorial

Introduction

Laravel is a powerful and flexible PHP framework designed for web application development. It follows the MVC (Model-View-Controller) architectural pattern and provides an expressive syntax. This tutorial will guide you through the process of setting up Laravel, developing a basic application, and understanding its core features.

Installation

To get started with Laravel, you'll need to ensure you have the following prerequisites installed:

  • PHP >= 7.3
  • Composer
  • MySQL or any other supported database

Once you have these prerequisites, you can install Laravel using Composer:

composer create-project --prefer-dist laravel/laravel myLaravelApp

This command will create a new Laravel project in a directory named myLaravelApp.

Directory Structure

Understanding the directory structure of a Laravel project is crucial. Here are some key directories:

  • app/: Contains the core code of your application including models, controllers, and middleware.
  • config/: Contains configuration files.
  • database/: Contains database migrations, seeders, and factories.
  • routes/: Contains all route definitions for the application.
  • resources/: Contains views, raw assets, and language files.
  • public/: The document root for the application, contains assets like images, JavaScript, and CSS.

Routing

Laravel uses a straightforward approach to routing. Routes are defined in the routes/web.php file for web routes. Here is an example of defining a route:

Route::get('/', function () {
    return view('welcome');
});
                

This route listens for GET requests to the root URL ("/") and returns the welcome view.

Controllers

Controllers handle the logic behind your application routes. To create a controller, you can use the Artisan command:

php artisan make:controller HomeController

This command will create a new controller file in the app/Http/Controllers directory named HomeController.php. Here is an example of a basic controller:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    public function index()
    {
        return view('home');
    }
}
                

In the routes file, you can now use this controller:

Route::get('/home', [HomeController::class, 'index']);
                

Views

Views are used to display data to the user. Laravel uses the Blade templating engine. Views are stored in the resources/views directory. Here is an example of a basic Blade view file:





    Home Page


    

Welcome to the Home Page