Backend Development

Getting Started with Laravel: A Beginner's Guide

Mayur Dabhi
Mayur Dabhi
February 16, 2026
12 min read

Laravel has revolutionized PHP development, transforming it from a language often criticized for its inconsistencies into a powerful ecosystem for building modern web applications. Whether you're a PHP developer looking to level up your skills or a newcomer to backend development, this comprehensive guide will walk you through everything you need to know to get started with Laravel.

Why Laravel?

Laravel is the most starred PHP framework on GitHub with over 75,000 stars. It's used by companies like Disney, BBC, Pfizer, and thousands of startups worldwide. Its elegant syntax and robust features make it the go-to choice for modern PHP development.

What is Laravel?

Laravel is a free, open-source PHP web framework created by Taylor Otwell in 2011. It follows the Model-View-Controller (MVC) architectural pattern and provides an expressive, elegant syntax that makes web development enjoyable and creative.

Here's what makes Laravel stand out:

User Controller Handles Requests Model Business Logic View Blade Templates DB Request Response

Laravel's MVC Architecture Flow

Prerequisites and Installation

Before diving into Laravel, make sure you have the following installed on your system:

Requirement Minimum Version Recommended
PHP 8.1 8.2+
Composer 2.0 Latest
Node.js 16.x 18.x+
Database MySQL 5.7 / PostgreSQL 10 MySQL 8.0 / PostgreSQL 15

Step-by-Step Installation

1

Install Composer

Composer is PHP's dependency manager. Download it from getcomposer.org or use your system's package manager.

2

Create New Laravel Project

Use the Laravel installer or Composer to create a fresh Laravel application.

Terminal
# Install Laravel installer globally
composer global require laravel/installer

# Create a new Laravel project
laravel new my-awesome-app

# OR use Composer directly
composer create-project laravel/laravel my-awesome-app

# Navigate to project directory
cd my-awesome-app

# Start the development server
php artisan serve
3

Configure Environment

Copy .env.example to .env and configure your database credentials.

4

Generate Application Key

Run php artisan key:generate to set your APP_KEY in the .env file.

Pro Tip

If you're using Laravel Sail, you can spin up a complete development environment with Docker using just ./vendor/bin/sail up. This includes PHP, MySQL, Redis, and more!

Understanding Laravel's Directory Structure

Laravel's directory structure is designed to be intuitive and organized. Here's what each main directory contains:

πŸ“ my-laravel-app/ πŸ“‚ app/ Models, Controllers, Middleware, Providers πŸ“‚ config/ Application configuration files (app.php, database.php) πŸ“‚ database/ Migrations, Seeders, Factories πŸ“‚ resources/ Views (Blade), CSS, JavaScript, Lang files πŸ“‚ routes/ web.php, api.php, console.php, channels.php πŸ“‚ public/ Entry point (index.php), Assets, Uploads πŸ“‚ storage/ & vendor/ Cache, logs, dependencies πŸ“‚ tests/ Feature & Unit tests

Routing Basics

Routes are the entry point to your Laravel application. They define how your application responds to HTTP requests.

Define routes in routes/web.php:

use Illuminate\Support\Facades\Route;

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

// Route to a controller
Route::get('/users', [UserController::class, 'index']);

// Different HTTP methods
Route::post('/users', [UserController::class, 'store']);
Route::put('/users/{id}', [UserController::class, 'update']);
Route::delete('/users/{id}', [UserController::class, 'destroy']);

Capture dynamic segments from the URL:

// Required parameter
Route::get('/user/{id}', function ($id) {
    return "User ID: " . $id;
});

// Optional parameter with default
Route::get('/user/{name?}', function ($name = 'Guest') {
    return "Hello, " . $name;
});

// Multiple parameters
Route::get('/posts/{post}/comments/{comment}', function ($postId, $commentId) {
    return "Post: $postId, Comment: $commentId";
});

// Regex constraints
Route::get('/user/{id}', function ($id) {
    return "User: " . $id;
})->where('id', '[0-9]+');

Name your routes for easy URL generation:

// Define named route
Route::get('/user/profile', [ProfileController::class, 'show'])
    ->name('profile');

// Generate URL to named route
$url = route('profile');

// Redirect to named route
return redirect()->route('profile');

// In Blade templates
<a href="{{ route('profile') }}">Profile</a>

// With parameters
Route::get('/user/{id}/profile', [ProfileController::class, 'show'])
    ->name('profile');

$url = route('profile', ['id' => 1]);

Group routes with shared attributes:

// Middleware group
Route::middleware(['auth'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
    Route::get('/settings', [SettingsController::class, 'index']);
});

// Prefix group
Route::prefix('admin')->group(function () {
    Route::get('/users', [AdminUserController::class, 'index']);
    // URL: /admin/users
});

// Combined attributes
Route::prefix('api')
    ->middleware('api')
    ->name('api.')
    ->group(function () {
        Route::get('/users', [ApiUserController::class, 'index'])
            ->name('users.index');
        // Name: api.users.index
    });

Controllers

Controllers group related request handling logic into single classes. They serve as the middleman between your routes and your application's business logic.

app/Http/Controllers/UserController.php
<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * Display a listing of users.
     */
    public function index()
    {
        $users = User::all();
        return view('users.index', compact('users'));
    }

    /**
     * Show the form for creating a new user.
     */
    public function create()
    {
        return view('users.create');
    }

    /**
     * Store a newly created user.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:8|confirmed',
        ]);

        $user = User::create([
            'name' => $validated['name'],
            'email' => $validated['email'],
            'password' => bcrypt($validated['password']),
        ]);

        return redirect()
            ->route('users.show', $user)
            ->with('success', 'User created successfully!');
    }

    /**
     * Display the specified user.
     */
    public function show(User $user)
    {
        return view('users.show', compact('user'));
    }
}
Artisan Tip

Generate controllers quickly with Artisan: php artisan make:controller UserController --resource creates a controller with all CRUD methods pre-defined!

Eloquent ORM: Working with Databases

Eloquent is Laravel's powerful ORM (Object-Relational Mapping) that makes database interactions a breeze. Each database table has a corresponding Model that you use to interact with that table.

PHP Code User::find(1) $user->posts Eloquent Query Builder Builds SQL queries PDO Database MySQL/PostgreSQL SQLite/SQL Server Returns Model instances / Collections

How Eloquent processes database queries

app/Models/User.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class User extends Model
{
    use HasFactory;

    // Mass assignable attributes
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    // Hidden from arrays/JSON
    protected $hidden = [
        'password',
        'remember_token',
    ];

    // Attribute casting
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
    ];

    // Relationship: User has many posts
    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    // Relationship: User belongs to many roles
    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }
}

Common Eloquent Operations

Eloquent Query Examples
// Retrieve all users
$users = User::all();

// Find by primary key
$user = User::find(1);
$user = User::findOrFail(1); // Throws 404 if not found

// Query with conditions
$activeUsers = User::where('status', 'active')
    ->where('age', '>', 18)
    ->orderBy('created_at', 'desc')
    ->get();

// First matching record
$admin = User::where('role', 'admin')->first();

// Create new record
$user = User::create([
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'password' => bcrypt('password'),
]);

// Update existing record
$user->update(['name' => 'Jane Doe']);

// Delete record
$user->delete();

// Soft delete (if enabled)
$user->delete(); // Marks as deleted
User::withTrashed()->get(); // Include soft deleted

// Eager loading relationships
$users = User::with(['posts', 'roles'])->get();

// Pagination
$users = User::paginate(15);

Blade Templates

Blade is Laravel's powerful templating engine that makes writing views elegant and efficient. It provides convenient shortcuts for common PHP control structures while being compiled into plain PHP code for optimal performance.

resources/views/layouts/app.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>@yield('title', 'My Laravel App')</title>
    @vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<body>
    <nav>
        @include('partials.navigation')
    </nav>

    <main>
        @yield('content')
    </main>

    <footer>
        @include('partials.footer')
    </footer>
</body>
</html>
resources/views/users/index.blade.php
@extends('layouts.app')

@section('title', 'All Users')

@section('content')
    <h1>Users</h1>

    {{-- Display success message --}}
    @if(session('success'))
        <div class="alert alert-success">
            {{ session('success') }}
        </div>
    @endif

    {{-- Loop through users --}}
    @forelse($users as $user)
        <div class="user-card">
            <h2>{{ $user->name }}</h2>
            <p>{{ $user->email }}</p>
            
            @if($user->isAdmin())
                <span class="badge">Admin</span>
            @endif
            
            <a href="{{ route('users.show', $user) }}">
                View Profile
            </a>
        </div>
    @empty
        <p>No users found.</p>
    @endforelse

    {{-- Pagination links --}}
    {{ $users->links() }}
@endsection

Blade Directives Quick Reference

Directive Purpose Example
{{ $var }} Echo escaped content {{ $user->name }}
{!! $var !!} Echo unescaped HTML {!! $post->content !!}
@if / @else Conditional statements @if($user) ... @endif
@foreach Loop through arrays @foreach($items as $item)
@forelse Loop with empty fallback @forelse ... @empty ... @endforelse
@auth / @guest Auth conditionals @auth Welcome! @endauth
@csrf CSRF token field <form>@csrf</form>
@method Form method spoofing @method('PUT')

Form Validation

Laravel provides several different approaches to validate incoming data. The most common method is using the validate method available on all incoming HTTP requests.

Form Validation Example
public function store(Request $request)
{
    $validated = $request->validate([
        'title' => 'required|string|max:255',
        'email' => 'required|email|unique:users,email',
        'body' => 'required|min:10',
        'category_id' => 'required|exists:categories,id',
        'tags' => 'array',
        'tags.*' => 'exists:tags,id',
        'publish_date' => 'nullable|date|after:today',
        'image' => 'nullable|image|mimes:jpg,png|max:2048',
    ]);

    // If validation fails, Laravel automatically redirects back
    // with errors. If it passes, continue with validated data.
    
    Post::create($validated);
    
    return redirect()->route('posts.index')
        ->with('success', 'Post created successfully!');
}
Important

Always validate user input! Never trust data from the client. Laravel's validation rules protect against common attacks and ensure data integrity.

Authentication Made Easy

Laravel makes implementing authentication incredibly simple. With Laravel Breeze or Jetstream, you can have a complete authentication system in minutes.

Setting Up Authentication with Breeze
# Install Laravel Breeze
composer require laravel/breeze --dev

# Install Breeze scaffolding
php artisan breeze:install

# Choose your stack:
# - blade (Traditional server-side)
# - react (React with Inertia)
# - vue (Vue with Inertia)
# - api (API only)

# Install dependencies and build assets
npm install && npm run dev

# Run migrations
php artisan migrate

This gives you complete registration, login, password reset, email verification, and password confirmation features out of the box!

πŸ‘€ User Login Form email + password Auth Validate & Hash Session Store user state 🏠 Home Laravel Authentication Flow Built-in CSRF protection, rate limiting, and secure password hashing

Essential Artisan Commands

Artisan is Laravel's command-line interface. It provides numerous helpful commands for development. Here are the most commonly used ones:

Command Description
php artisan serve Start development server
php artisan make:model Post -mcr Create model with migration, controller, and resource
php artisan migrate Run database migrations
php artisan migrate:fresh --seed Fresh migration with seeders
php artisan db:seed Run database seeders
php artisan tinker Interactive REPL for Laravel
php artisan route:list List all registered routes
php artisan cache:clear Clear application cache
php artisan config:clear Clear configuration cache
php artisan optimize Cache config, routes, and views

Next Steps

Congratulations! You now have a solid foundation in Laravel. Here's what to explore next:

Continue Learning

  • Middleware: Learn to filter HTTP requests (authentication, logging, CORS)
  • API Development: Build RESTful APIs with Laravel Sanctum
  • Queues & Jobs: Handle time-consuming tasks asynchronously
  • Events & Listeners: Decouple your application logic
  • Testing: Write feature and unit tests with PHPUnit
  • Deployment: Deploy to production with Laravel Forge or Vapor
Helpful Resources

Official Documentation: laravel.com/docs
Laracasts: laracasts.com (video tutorials)
Laravel News: laravel-news.com
Laravel Daily: laraveldaily.com

"Laravel has everything you need to build modern web applications. Start simple, and as you grow, Laravel grows with you."
β€” Taylor Otwell, Creator of Laravel

Laravel is more than just a frameworkβ€”it's an ecosystem designed to make you a more productive developer. With its elegant syntax, powerful features, and vibrant community, you're now equipped to build amazing web applications. Happy coding! πŸš€

Laravel PHP MVC Web Development Backend Tutorial Beginners
Mayur Dabhi

Mayur Dabhi

Full Stack Developer with 5+ years of experience building scalable web applications with Laravel, React, and Node.js.