Laravel Tutorial

Laravel is one of the most popular PHP frameworks for building web applications. It simplifies complex tasks, offers a clean and easy to understand syntax, and provides numerous features that make web development faster and more efficient. Whether you’re new to web development or an experienced developer, Laravel provides a robust toolkit that caters to various needs.

In this blog, we’ll cover the basics of Laravel, walk through the steps to install it, and build a simple web application with essential explanations along the way.

Table of Contents

  1. What is Laravel?
  2. Why Use Laravel?
  3. Installing Laravel
  4. Basic Laravel Concepts
  5. Creating a Simple Web Application
  6. Routing in Laravel
  7. Controllers in Laravel
  8. Views and Blade Templating Engine
  9. Eloquent ORM: Working with Databases
  10. Laravel Migrations
  11. Conclusion

What is Laravel?

Laravel is a free, open-source PHP framework that provides tools and resources for building modern PHP applications. It follows the MVC (Model-View-Controller) architecture pattern and emphasizes simplicity and elegance.

Key Features of Laravel

  • Routing :- Simplified URL routing configuration.
  • Eloquent ORM :- An easy-to-use database management system.
  • Blade Templating :- A powerful templating engine.
  • Middleware :- Allows filtering HTTP requests entering the application.
  • Security :- Laravel has built-in security features like CSRF protection, password hashing, and encryption.

Why Use Laravel?

Laravel streamlines the development process by offering out of the box solutions for common tasks like routing, authentication, session management, and more. Here’s why many developers choose Laravel.

  • Elegant Syntax :- Laravel provides an expressive and clean syntax.
  • Community Support :- One of the largest and most active communities.
  • Rich Ecosystem :- Tools like Laravel Forge, Nova, and Envoyer extend its functionalities.
  • Easy Integration :- Laravel integrates seamlessly with frontend technologies like Vue.js and React.
  • Modular Structure :- Easy to scale and maintain large applications

Installing Laravel

Before installing Laravel, you need to ensure that your system has the following prerequisites.

  • PHP >= 8.1
  • Composer (Dependency Manager for PHP)
  • MySQL or any other database supported by Laravel

Step 1 : Install Composer

If you don’t have Composer installed, download it from Composer’s official website. Composer will help manage dependencies for Laravel.

Step 2 : Install Laravel

Once Composer is installed, you can create a new Laravel project by running the following command in your terminal.

composer create-project –prefer-dist laravel/laravel myFirstApp

This command will create a new directory myFirstApp containing your Laravel project.

Step 3: Serve Your Application

Navigate into your project directory and start the local development server.

cd myFirstApp

php artisan serve

This will run your Laravel application on http://localhost:8000.

Basic Laravel Concepts

Before we dive into building the application, it’s essential to understand some basic Laravel concepts.

MVC Architecture

Laravel is built on the MVC (Model-View-Controller) design pattern. This pattern separates the application logic into three main components.

  • Model: Represents the data structure of your application.
  • View: Handles what the user sees (UI).
  • Controller: Manages the communication between the Model and the View.

Artisan Console

Laravel’s Artisan is a command-line interface that provides various helpful commands to streamline the development process, such as generating controllers, models, and migrations.

For example, to generate a controller, you can use :-

php artisan make:controller MyController

Creating a Simple Web Application

Let’s create a simple “To Do List” web application using Laravel.

Step 1 : Setting Up Routes

Laravel routes are defined in the routes/web.php file. Routes define the URLs your application will respond to and which controller or closure should handle the request.

Example route for displaying the homepage :-

Route::get(‘/’, function () {

    return view(‘welcome’); });

You can create a new route for the “To Do List” page :-

Route::get(‘/todos’, [TodoController::class, ‘index’]);

Step 2 : Create a Controller

Next, we need a controller to handle the logic for our “To-Do List”. Use the Artisan command to generate a new controller :-

php artisan make:controller TodoController

Now, open the app/Http/Controllers/TodoController.php file and add the following code :-

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TodoController extends Controller

{

    public function index()

    {

        $todos = [‘Buy groceries’, ‘Complete Laravel tutorial’, ‘Work on project’];

        return view(‘todos.index’, compact(‘todos’));

    }

}

This controller retrieves a list of to do items and passes them to the view.

Routing in Laravel

Routing in Laravel is very flexible. You can define GET, POST, PUT, DELETE routes, and even resource routes. A resource route maps typical CRUD (Create, Read, Update, Delete) routes for a controller.

Example

Route::resource(‘tasks’, TaskController::class);

This will automatically create routes for the following actions :-

  • GET /tasks
  • POST /tasks
  • PUT /tasks/{id}
  • DELETE /tasks/{id}

Controllers in Laravel

Controllers are the place where you handle your application logic. Each method inside a controller typically handles a specific route.

Example of a controller method :-

public function store(Request $request)

{

    $task = new Task();

    $task->name = $request->input(‘name’);

    $task->save();

    return redirect()->back();

}

In this example, we are receiving data from the form, saving it to the database, and then redirecting the user back to the previous page.

Views and Blade Templating Engine

Laravel uses Blade, a simple yet powerful templating engine, to create views. Blade allows you to use plain PHP in your views with easy to understand syntax.

Example of a Blade template :-

<!DOCTYPE html>

<html>

<head>

    <title>Todo List</title>

</head>

<body>

    <h1>My Todo List</h1>

    <ul>

        @foreach($todos as $todo)

            <li>{{ $todo }}</li>

        @endforeach

    </ul>

</body>

</html>

Blade provides several directives like @foreach, @if, @include, etc., to make working with views simpler.

Eloquent ORM : Working with Databases

Laravel’s Eloquent ORM is an elegant way to interact with databases. It allows you to define models that correspond to database tables, and provides methods to easily retrieve, insert, update, and delete data.

Example of an Eloquent model :-

class Task extends Model { protected $fillable = [‘name’]; }

Fetching all tasks :-

$tasks = Task::all();

Inserting a new task :-

$task = Task::create([‘name’ => ‘New Task’]);

Laravel Migrations

Migrations are version control for your database. They allow you to define and update database schema over time.

To create a migration :-

php artisan make:migration create_tasks_table

Then, in your migration file, define the table structure :-

Schema::create(‘tasks’, function (Blueprint $table) {

    $table->id();

    $table->string(‘name’);

    $table->timestamps();

});

Run the migration with :-

php artisan migrate

This will create the tasks table in your database.

Conclusion

Laravel provides a clean, efficient, and powerful platform for building web applications. With its easy to understand syntax, comprehensive toolset, and a strong community, Laravel simplifies many common development tasks, allowing developers to focus on creating great applications.

Whether you are creating a simple to do list or a complex enterprise system, Laravel has the tools and flexibility to make your development journey smoother. Start experimenting with the concepts we’ve covered, and before you know it, you’ll be building robust and feature rich applications with ease.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top