Laravel Framework

Contents

Introduction to Laravel

Laravel is a PHP web application framework known for its elegant syntax and robust features. It follows the MVC pattern and provides extensive tools for modern web development.

Key Features:

  • Elegant syntax and modern toolkit
  • Robust dependency injection container
  • Database abstraction layer
  • Artisan command-line interface
  • Queue system for background jobs
  • Real-time events

Why Laravel?

Laravel combines powerful features with developer-friendly syntax, making it ideal for both small and enterprise applications. It provides a complete ecosystem with tools like Forge, Vapor, and Nova.

Routing and Controllers

Basic Routing

// routes/web.php use Illuminate\Support\Facades\Route; Route::get('/', function () { return view('welcome'); }); Route::get('/users', [UserController::class, 'index']); Route::post('/users', [UserController::class, 'store']); Route::get('/users/{id}', [UserController::class, 'show']); // Resource Controller Route::resource('posts', PostController::class);

Controllers

namespace App\Http\Controllers; use App\Models\User; use Illuminate\Http\Request; class UserController extends Controller { public function index() { $users = User::all(); return view('users.index', ['users' => $users]); } public function store(Request $request) { $validated = $request->validate([ 'name' => 'required|max:255', 'email' => 'required|email|unique:users', ]); $user = User::create($validated); return redirect()->route('users.show', $user); } }

Blade Templates

Basic Syntax

@extends('layouts.app') @section('content')

Users

@foreach ($users as $user)

{{ $user->name }}

@if ($user->isAdmin) Admin @endif
@endforeach @empty($users)

No users found.

@endempty @endsection

Components

namespace App\View\Components; class Alert extends Component { public $type; public $message; public function __construct($type, $message) { $this->type = $type; $this->message = $message; } public function render() { return view('components.alert'); } }
{{ $message }}

Eloquent ORM

Models

namespace App\Models; use Illuminate\Database\Eloquent\Model; class Post extends Model { protected $fillable = ['title', 'content', 'user_id']; public function user() { return $this->belongsTo(User::class); } public function comments() { return $this->hasMany(Comment::class); } public function tags() { return $this->belongsToMany(Tag::class); } }

Queries

// Basic queries $users = User::all(); $user = User::find(1); $activeUsers = User::where('active', true)->get(); // Relationships $user->posts()->create([ 'title' => 'New Post', 'content' => 'Post content' ]); // Advanced queries $posts = Post::with('user', 'comments') ->whereHas('comments', function ($query) { $query->where('approved', true); }) ->orderBy('created_at', 'desc') ->paginate(20);

Authentication and Authorization

Authentication

// config/auth.php 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'sanctum', 'provider' => 'users', ], ], // Routes Route::middleware(['auth'])->group(function () { Route::get('/dashboard', function () { return view('dashboard'); }); });

Authorization

// App\Policies\PostPolicy.php class PostPolicy { public function update(User $user, Post $post) { return $user->id === $post->user_id; } } // Usage in controllers $this->authorize('update', $post); // Usage in blade @can('update', $post) Edit @endcan

Artisan Console

Common Commands

# Create new controller php artisan make:controller UserController --resource # Create model with migration php artisan make:model Post -m # Database migrations php artisan migrate php artisan migrate:rollback php artisan migrate:fresh --seed # Create custom command php artisan make:command SendEmails

Custom Commands

namespace App\Console\Commands; use Illuminate\Console\Command; class SendEmails extends Command { protected $signature = 'emails:send {user? : The ID of the user}'; protected $description = 'Send emails to users'; public function handle() { $userId = $this->argument('user'); if ($userId) { // Send to specific user } else { // Send to all users } $this->info('Emails sent successfully!'); } }

Testing

Feature Tests

namespace Tests\Feature; use Tests\TestCase; use App\Models\User; class UserTest extends TestCase { public function test_user_can_view_posts() { $user = User::factory()->create(); $response = $this->actingAs($user) ->get('/posts'); $response->assertStatus(200) ->assertViewIs('posts.index'); } }

Unit Tests

namespace Tests\Unit; use PHPUnit\Framework\TestCase; use App\Services\Calculator; class CalculatorTest extends TestCase { public function test_it_adds_numbers() { $calculator = new Calculator(); $result = $calculator->add(2, 2); $this->assertEquals(4, $result); } }

Deployment

Deployment Checklist:

  • Configure environment variables
  • Optimize autoloader
  • Cache configuration
  • Set up queue workers
  • Configure web server

Optimization Commands

# Optimize for production php artisan config:cache php artisan route:cache php artisan view:cache # Install dependencies composer install --no-dev --optimize-autoloader # Environment setup php artisan key:generate php artisan storage:link # Database migrations php artisan migrate --force