# Laravel Framework Laravel is a PHP web application framework designed with expressive, elegant syntax to make development enjoyable and productive. The framework provides a robust foundation for building modern web applications by offering a comprehensive ecosystem of tools including routing, dependency injection, database abstraction, queue management, real-time event broadcasting, and much more. Laravel follows the MVC (Model-View-Controller) architectural pattern and emphasizes convention over configuration while remaining highly flexible and extensible. The Laravel Framework (version 13.2.0) serves as the core engine powering Laravel applications. This repository contains the foundational components that handle HTTP requests, manage database operations through Eloquent ORM, process background jobs, send notifications, handle authentication, and provide dozens of other essential services. Each component is designed to work independently or as part of the integrated framework, allowing developers to use only what they need while maintaining full compatibility with the broader Laravel ecosystem. ## Service Container - Dependency Injection The Laravel Service Container is a powerful dependency injection container that manages class dependencies and performs dependency injection. It resolves classes automatically by inspecting constructor type-hints and can be configured with explicit bindings for interfaces and abstract classes. ```php bind(PaymentGatewayInterface::class, StripePaymentGateway::class); // Singleton binding - only one instance will ever be created $container->singleton(DatabaseConnection::class, function ($container) { return new DatabaseConnection( host: config('database.host'), database: config('database.name'), username: config('database.username'), password: config('database.password') ); }); // Scoped binding - fresh instance per request lifecycle $container->scoped(ShoppingCart::class, function ($container) { return new ShoppingCart($container->make(SessionManager::class)); }); // Contextual binding - different implementations based on context $container->when(PhotoController::class) ->needs(StorageInterface::class) ->give(S3Storage::class); $container->when(VideoController::class) ->needs(StorageInterface::class) ->give(LocalStorage::class); // Resolve dependencies automatically $userController = $container->make(UserController::class); // Call methods with automatic dependency injection $result = $container->call([UserController::class, 'store'], ['request' => $request]); // Bind using attributes (PHP 8+) #[Singleton] class CacheService { public function __construct( private RedisConnection $redis ) {} } // Tag multiple bindings $container->bind(SpeedReport::class); $container->bind(MemoryReport::class); $container->tag([SpeedReport::class, MemoryReport::class], 'reports'); // Resolve all tagged bindings $reports = $container->tagged('reports'); foreach ($reports as $report) { $report->generate(); } ``` ## Routing - HTTP Routes The Laravel Router provides a simple and expressive way to define application routes. Routes map HTTP requests to controller actions or closures, supporting RESTful resource routing, route groups, middleware, and parameter constraints. ```php where('id', '[0-9]+'); // Named routes Route::get('/profile', [ProfileController::class, 'show'])->name('profile.show'); $url = route('profile.show'); // Generate URL // Route groups with shared attributes Route::prefix('admin') ->middleware(['auth', 'admin']) ->name('admin.') ->group(function () { Route::get('/dashboard', [AdminController::class, 'dashboard'])->name('dashboard'); Route::get('/users', [AdminController::class, 'users'])->name('users'); Route::get('/settings', [AdminController::class, 'settings'])->name('settings'); }); // RESTful resource controller - generates index, create, store, show, edit, update, destroy routes Route::resource('posts', PostController::class); // API resource (excludes create and edit forms) Route::apiResource('products', ProductController::class); // Nested resources Route::resource('posts.comments', CommentController::class)->shallow(); // Route model binding Route::get('/posts/{post}', function (Post $post) { return $post; // Automatically resolved by ID }); // Custom route model binding Route::get('/posts/{post:slug}', function (Post $post) { return $post; // Resolved by slug column }); // Fallback route for 404 handling Route::fallback(function () { return response()->view('errors.404', [], 404); }); // Redirect routes Route::redirect('/old-page', '/new-page', 301); Route::permanentRedirect('/legacy', '/modern'); // View routes (no controller needed) Route::view('/welcome', 'welcome', ['name' => 'Laravel']); // Rate limiting Route::middleware('throttle:60,1')->group(function () { Route::get('/api/data', [DataController::class, 'index']); }); ``` ## HTTP Request Handling The Request class provides an object-oriented way to interact with the current HTTP request, including input data, files, headers, and session data. It extends Symfony's HttpFoundation Request with additional Laravel-specific functionality. ```php all(); // Get specific input values $name = $request->input('name'); $email = $request->input('email', 'default@example.com'); // Get nested input $city = $request->input('address.city'); // Check if input exists if ($request->has('newsletter')) { // Subscribe to newsletter } // Get only specific fields $credentials = $request->only(['email', 'password']); // Get all except specific fields $data = $request->except(['_token', 'password_confirmation']); // Boolean input $remember = $request->boolean('remember'); // Date input $birthdate = $request->date('birthdate', 'Y-m-d'); // File uploads if ($request->hasFile('avatar')) { $file = $request->file('avatar'); if ($file->isValid()) { $path = $file->store('avatars', 'public'); $originalName = $file->getClientOriginalName(); $extension = $file->extension(); $size = $file->getSize(); } } // Request information $method = $request->method(); $url = $request->url(); $fullUrl = $request->fullUrl(); $path = $request->path(); $ip = $request->ip(); $userAgent = $request->userAgent(); // Check request type if ($request->expectsJson()) { return response()->json(['status' => 'success']); } if ($request->ajax()) { // Handle AJAX request } // Headers $contentType = $request->header('Content-Type'); $bearerToken = $request->bearerToken(); // Validate and get validated data $validated = $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:users', 'password' => 'required|min:8|confirmed', ]); // Get authenticated user $user = $request->user(); return User::create($validated); } } ``` ## Eloquent ORM - Models Eloquent is Laravel's ActiveRecord ORM implementation that provides a beautiful, simple way to interact with your database. Each database table has a corresponding Model class used for interacting with that table, supporting relationships, query scopes, accessors/mutators, and events. ```php 'datetime', 'password' => 'hashed', 'settings' => 'array', 'is_admin' => 'boolean', ]; } // Accessor (computed attribute) protected function fullName(): Attribute { return Attribute::make( get: fn () => "{$this->first_name} {$this->last_name}", ); } // Mutator protected function email(): Attribute { return Attribute::make( set: fn (string $value) => strtolower($value), ); } // Relationships public function posts(): HasMany { return $this->hasMany(Post::class); } public function profile(): HasOne { return $this->hasOne(Profile::class); } public function roles(): BelongsToMany { return $this->belongsToMany(Role::class)->withTimestamps(); } // Query scope public function scopeActive($query) { return $query->where('active', true); } public function scopeOfType($query, string $type) { return $query->where('type', $type); } } // Usage examples // Create $user = User::create([ 'name' => 'John Doe', 'email' => 'john@example.com', 'password' => 'secret123', ]); // Find $user = User::find(1); $user = User::findOrFail(1); $user = User::where('email', 'john@example.com')->first(); // Update $user->update(['name' => 'Jane Doe']); User::where('active', false)->update(['status' => 'inactive']); // Delete $user->delete(); User::destroy([1, 2, 3]); // Query with relationships $users = User::with(['posts', 'profile']) ->active() ->ofType('premium') ->orderBy('created_at', 'desc') ->paginate(15); // Lazy eager loading $user->load('posts.comments'); ``` ## Eloquent Query Builder The Eloquent Query Builder provides a fluent interface for constructing database queries. It supports all common SQL operations while protecting against SQL injection through parameter binding. ```php get(); // Complex where clauses $users = User::where('status', 'active') ->where('age', '>=', 18) ->orWhere('is_admin', true) ->get(); // Where with closures (grouped conditions) $users = User::where(function ($query) { $query->where('status', 'active') ->orWhere('status', 'pending'); })->where('age', '>=', 18)->get(); // WhereIn, WhereNotIn, WhereBetween $users = User::whereIn('role', ['admin', 'editor'])->get(); $users = User::whereBetween('created_at', [$startDate, $endDate])->get(); $users = User::whereNull('deleted_at')->get(); // Ordering and limiting $users = User::orderBy('name', 'asc') ->orderByDesc('created_at') ->take(10) ->skip(20) ->get(); // Aggregates $count = User::count(); $maxAge = User::max('age'); $avgSalary = User::where('department', 'engineering')->avg('salary'); $total = Order::sum('amount'); // Selecting specific columns $users = User::select('id', 'name', 'email')->get(); $users = User::select('name', DB::raw('COUNT(*) as post_count')) ->join('posts', 'users.id', '=', 'posts.user_id') ->groupBy('users.id', 'users.name') ->get(); // Joins $posts = Post::join('users', 'posts.user_id', '=', 'users.id') ->leftJoin('categories', 'posts.category_id', '=', 'categories.id') ->select('posts.*', 'users.name as author', 'categories.name as category') ->get(); // Subqueries $users = User::addSelect([ 'last_post_created_at' => Post::select('created_at') ->whereColumn('user_id', 'users.id') ->latest() ->limit(1) ])->get(); // Chunking for large datasets User::chunk(100, function ($users) { foreach ($users as $user) { // Process user } }); // Lazy collections for memory efficiency User::lazy()->each(function ($user) { // Process one user at a time }); // Insert, Update, Delete via Query Builder DB::table('users')->insert([ 'name' => 'John', 'email' => 'john@example.com', ]); DB::table('users') ->where('id', 1) ->update(['name' => 'Jane']); DB::table('users')->where('active', false)->delete(); // Upsert (insert or update) User::upsert([ ['email' => 'john@example.com', 'name' => 'John'], ['email' => 'jane@example.com', 'name' => 'Jane'], ], ['email'], ['name']); // Transactions DB::transaction(function () { User::create([...]); Profile::create([...]); }, 5); // 5 retry attempts on deadlock ``` ## Database Migrations Migrations provide version control for your database schema, allowing teams to define and share database structure. Each migration contains `up()` and `down()` methods for creating and rolling back changes. ```php id(); $table->foreignId('user_id')->constrained()->cascadeOnDelete(); $table->foreignId('category_id')->nullable()->constrained()->nullOnDelete(); $table->string('title'); $table->string('slug')->unique(); $table->text('excerpt')->nullable(); $table->longText('content'); $table->enum('status', ['draft', 'published', 'archived'])->default('draft'); $table->boolean('featured')->default(false); $table->json('metadata')->nullable(); $table->timestamp('published_at')->nullable(); $table->timestamps(); $table->softDeletes(); // Indexes $table->index(['status', 'published_at']); $table->fullText('content'); }); } public function down(): void { Schema::dropIfExists('posts'); } }; // Modifying existing tables return new class extends Migration { public function up(): void { Schema::table('users', function (Blueprint $table) { $table->string('phone')->nullable()->after('email'); $table->string('avatar')->nullable(); $table->renameColumn('name', 'full_name'); $table->dropColumn('legacy_field'); $table->index('phone'); }); } public function down(): void { Schema::table('users', function (Blueprint $table) { $table->dropIndex(['phone']); $table->dropColumn(['phone', 'avatar']); $table->renameColumn('full_name', 'name'); $table->string('legacy_field')->nullable(); }); } }; ``` ```bash # Run migrations php artisan migrate # Rollback last migration batch php artisan migrate:rollback # Reset all migrations php artisan migrate:reset # Refresh (rollback all and re-run) php artisan migrate:refresh --seed # Show migration status php artisan migrate:status ``` ## Events and Listeners Laravel's event system provides a simple observer pattern implementation, allowing you to subscribe and listen for events in your application. Events serve as a great way to decouple various aspects of your application. ```php order->user->email) ->send(new OrderConfirmation($event->order)); } public function failed(OrderPlaced $event, \Throwable $exception): void { // Handle failure } } // Register in EventServiceProvider protected $listen = [ OrderPlaced::class => [ SendOrderConfirmation::class, UpdateInventory::class, NotifyWarehouse::class, ], ]; // Dispatch events use App\Events\OrderPlaced; use Illuminate\Support\Facades\Event; // Method 1: Static dispatch OrderPlaced::dispatch($order); // Method 2: Event facade Event::dispatch(new OrderPlaced($order)); // Method 3: event() helper event(new OrderPlaced($order)); // Register listeners dynamically Event::listen(OrderPlaced::class, function (OrderPlaced $event) { // Handle event }); // Wildcard listeners Event::listen('order.*', function (string $eventName, array $data) { // Handle any order.* event }); // Model events class User extends Model { protected static function booted(): void { static::creating(function (User $user) { $user->uuid = Str::uuid(); }); static::created(function (User $user) { event(new UserRegistered($user)); }); static::deleting(function (User $user) { $user->posts()->delete(); }); } } ``` ## Queue Jobs Laravel queues provide a unified API for deferring time-consuming tasks to be processed in the background, dramatically speeding up web requests. Jobs can be dispatched to various queue backends including Redis, Amazon SQS, Beanstalkd, and databases. ```php podcast->process(); // Release back to queue with delay if needed if ($this->podcast->needsMoreProcessing()) { $this->release(60); } } public function middleware(): array { return [ new WithoutOverlapping($this->podcast->id), new RateLimited('podcasts'), ]; } public function failed(\Throwable $exception): void { // Send failure notification } public function retryUntil(): \DateTime { return now()->addHours(24); } } // Dispatch jobs use App\Jobs\ProcessPodcast; // Basic dispatch ProcessPodcast::dispatch($podcast); // Dispatch to specific queue ProcessPodcast::dispatch($podcast)->onQueue('processing'); // Dispatch with delay ProcessPodcast::dispatch($podcast)->delay(now()->addMinutes(10)); // Dispatch to specific connection ProcessPodcast::dispatch($podcast)->onConnection('sqs'); // Conditional dispatch ProcessPodcast::dispatchIf($shouldProcess, $podcast); ProcessPodcast::dispatchUnless($shouldSkip, $podcast); // Dispatch after response sent ProcessPodcast::dispatchAfterResponse($podcast); // Job chains Bus::chain([ new ProcessPodcast($podcast), new OptimizePodcast($podcast), new ReleasePodcast($podcast), ])->onQueue('podcasts')->dispatch(); // Job batches Bus::batch([ new ProcessPodcast($podcast1), new ProcessPodcast($podcast2), new ProcessPodcast($podcast3), ]) ->then(function (Batch $batch) { // All jobs completed successfully }) ->catch(function (Batch $batch, \Throwable $e) { // First batch job failure detected }) ->finally(function (Batch $batch) { // Batch has finished executing }) ->name('Process Podcasts') ->allowFailures() ->dispatch(); ``` ```bash # Process queue jobs php artisan queue:work # Process jobs from specific queue php artisan queue:work --queue=high,default,low # Process single job php artisan queue:work --once # Restart workers after code changes php artisan queue:restart # Failed jobs php artisan queue:failed php artisan queue:retry all php artisan queue:flush ``` ## Validation Laravel provides several approaches to validate incoming data. The most common is using the `validate` method on incoming HTTP requests, which throws a ValidationException if validation fails. ```php validate([ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:users,email', 'password' => 'required|min:8|confirmed', 'age' => 'nullable|integer|min:18|max:120', 'website' => 'nullable|url', 'avatar' => 'nullable|image|max:2048|dimensions:min_width=100,min_height=100', 'tags' => 'array|max:5', 'tags.*' => 'string|max:50', 'address.city' => 'required|string', 'address.zip' => 'required|regex:/^\d{5}(-\d{4})?$/', ]); return User::create($validated); } public function update(Request $request, User $user) { // Validation with custom messages $validated = $request->validate([ 'name' => 'required|string|max:255', 'email' => ['required', 'email', Rule::unique('users')->ignore($user->id)], ], [ 'name.required' => 'Please provide your name.', 'email.unique' => 'This email is already registered.', ]); $user->update($validated); return $user; } public function import(Request $request) { // Manual validator for custom handling $validator = Validator::make($request->all(), [ 'file' => 'required|file|mimes:csv,xlsx|max:10240', ]); if ($validator->fails()) { return response()->json([ 'errors' => $validator->errors(), ], 422); } // Additional validation after initial rules pass $validator->after(function ($validator) use ($request) { if ($this->hasDuplicateRows($request->file('file'))) { $validator->errors()->add('file', 'The file contains duplicate rows.'); } }); if ($validator->fails()) { return back()->withErrors($validator)->withInput(); } return $this->processImport($validator->validated()); } } // Form Request for complex validation namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Rules\Password; class StoreUserRequest extends FormRequest { public function authorize(): bool { return $this->user()->isAdmin(); } public function rules(): array { return [ 'name' => ['required', 'string', 'max:255'], 'email' => ['required', 'email', 'unique:users'], 'password' => [ 'required', 'confirmed', Password::min(8) ->letters() ->mixedCase() ->numbers() ->symbols() ->uncompromised(), ], 'role' => ['required', Rule::in(['user', 'admin', 'moderator'])], ]; } public function messages(): array { return [ 'password.uncompromised' => 'This password has appeared in a data breach.', ]; } protected function prepareForValidation(): void { $this->merge([ 'email' => strtolower($this->email), ]); } } // Custom validation rule namespace App\Rules; use Illuminate\Contracts\Validation\ValidationRule; class Uppercase implements ValidationRule { public function validate(string $attribute, mixed $value, \Closure $fail): void { if (strtoupper($value) !== $value) { $fail('The :attribute must be uppercase.'); } } } ``` ## Cache Laravel provides an expressive, unified API for various caching backends including Memcached, Redis, DynamoDB, and file-based caching. Caching improves application performance by storing expensive computation results. ```php addMinutes(10)); Cache::put('key', 'value', 600); // seconds $value = Cache::get('key'); $value = Cache::get('key', 'default'); // Check existence if (Cache::has('key')) { // Key exists } // Get and delete $value = Cache::pull('key'); // Store forever Cache::forever('key', 'value'); // Delete Cache::forget('key'); Cache::flush(); // Clear all cache // Increment/Decrement Cache::increment('counter'); Cache::increment('counter', 5); Cache::decrement('counter'); // Remember - get or store $users = Cache::remember('users', 3600, function () { return User::all(); }); // Remember forever $settings = Cache::rememberForever('settings', function () { return Setting::all()->pluck('value', 'key'); }); // Atomic locks $lock = Cache::lock('processing', 10); if ($lock->get()) { try { // Process exclusively for 10 seconds } finally { $lock->release(); } } // Block until lock available Cache::lock('processing', 10)->block(5, function () { // Lock acquired, max 5 second wait }); // Cache tags (Redis/Memcached only) Cache::tags(['users', 'profiles'])->put('user:1', $user, 3600); Cache::tags(['users'])->flush(); // Clear all user-related cache // Multiple stores Cache::store('redis')->put('key', 'value', 600); Cache::store('file')->get('key'); // Memoization (request-scoped cache) $user = Cache::memo()->remember('current_user', function () { return auth()->user(); }); ``` ## Mail Laravel's email API provides a clean, simple interface over the popular Symfony Mailer component. Mail supports various drivers including SMTP, Mailgun, Postmark, Amazon SES, and Resend. ```php order->id} Shipped", tags: ['orders', 'shipping'], metadata: ['order_id' => $this->order->id], ); } public function content(): Content { return new Content( markdown: 'emails.orders.shipped', with: [ 'trackingUrl' => $this->order->tracking_url, 'estimatedDelivery' => $this->order->estimated_delivery, ], ); } public function attachments(): array { return [ Attachment::fromPath('/path/to/invoice.pdf') ->as('invoice.pdf') ->withMime('application/pdf'), Attachment::fromStorage('invoices/invoice.pdf'), Attachment::fromData(fn () => $this->order->generateLabel(), 'shipping-label.pdf'), ]; } } // Sending mail use App\Mail\OrderShipped; use Illuminate\Support\Facades\Mail; // Send immediately Mail::to($user)->send(new OrderShipped($order)); // Queue for background sending Mail::to($user)->queue(new OrderShipped($order)); // Delayed sending Mail::to($user) ->later(now()->addMinutes(10), new OrderShipped($order)); // Multiple recipients Mail::to($user) ->cc($managers) ->bcc('archive@example.com') ->send(new OrderShipped($order)); // Send to collection of users Mail::to($subscribers)->send(new Newsletter($content)); // Raw message Mail::raw('Plain text email content', function ($message) { $message->to('user@example.com') ->subject('Plain Text Email'); }); // Test/Preview mailable return (new OrderShipped($order))->render(); ``` ## Notifications Laravel notifications provide support for sending notifications across a variety of delivery channels including email, SMS, Slack, and database storage. Notifications can also be broadcast for real-time display in web interfaces. ```php subject('Invoice Paid') ->greeting("Hello {$notifiable->name}!") ->line("Invoice #{$this->invoice->id} has been paid.") ->line("Amount: \${$this->invoice->amount}") ->action('View Invoice', url("/invoices/{$this->invoice->id}")) ->line('Thank you for your business!'); } public function toArray(object $notifiable): array { return [ 'invoice_id' => $this->invoice->id, 'amount' => $this->invoice->amount, 'paid_at' => now()->toISOString(), ]; } public function toSlack(object $notifiable): SlackMessage { return (new SlackMessage) ->success() ->content("Invoice #{$this->invoice->id} paid!") ->attachment(function ($attachment) { $attachment->title('Invoice Details') ->fields([ 'Amount' => "\${$this->invoice->amount}", 'Customer' => $this->invoice->customer->name, ]); }); } } // Send notifications use App\Notifications\InvoicePaid; // To a single user $user->notify(new InvoicePaid($invoice)); // To multiple users Notification::send($users, new InvoicePaid($invoice)); // On-demand notification (no user model) Notification::route('mail', 'admin@example.com') ->route('slack', 'webhook-url') ->notify(new InvoicePaid($invoice)); // Access stored notifications foreach ($user->notifications as $notification) { echo $notification->type; echo $notification->data['invoice_id']; } // Mark as read $user->unreadNotifications->markAsRead(); ``` ## Middleware Middleware provides a mechanism for filtering HTTP requests entering your application. Laravel includes middleware for authentication, CORS, CSRF protection, and more. You can also create custom middleware. ```php user()?->isAdmin()) { abort(403, 'Unauthorized action.'); } return $next($request); } } // Middleware with parameters class RoleMiddleware { public function handle(Request $request, Closure $next, string ...$roles): Response { if (! $request->user()?->hasAnyRole($roles)) { abort(403); } return $next($request); } } // After middleware (runs after response) class AddSecurityHeaders { public function handle(Request $request, Closure $next): Response { $response = $next($request); $response->headers->set('X-Content-Type-Options', 'nosniff'); $response->headers->set('X-Frame-Options', 'DENY'); $response->headers->set('X-XSS-Protection', '1; mode=block'); return $response; } } // Terminable middleware (runs after response sent) class LogRequest { public function handle(Request $request, Closure $next): Response { return $next($request); } public function terminate(Request $request, Response $response): void { Log::info('Request completed', [ 'url' => $request->fullUrl(), 'method' => $request->method(), 'status' => $response->getStatusCode(), 'duration' => microtime(true) - LARAVEL_START, ]); } } // Register in bootstrap/app.php ->withMiddleware(function (Middleware $middleware) { $middleware->alias([ 'admin' => EnsureUserIsAdmin::class, 'role' => RoleMiddleware::class, ]); $middleware->append(AddSecurityHeaders::class); $middleware->group('api', [ 'throttle:api', \Illuminate\Routing\Middleware\SubstituteBindings::class, ]); }) // Use in routes Route::get('/admin', [AdminController::class, 'index']) ->middleware('admin'); Route::get('/dashboard', [DashboardController::class, 'index']) ->middleware('role:admin,editor'); ``` ## Collections Laravel Collections provide a fluent, convenient wrapper for working with arrays of data. The Collection class provides dozens of methods for mapping, filtering, reducing, and transforming data. ```php map(fn ($item) => $item * 2); // [2, 4, 6] $plucked = collect([ ['name' => 'John', 'email' => 'john@example.com'], ['name' => 'Jane', 'email' => 'jane@example.com'], ])->pluck('email'); // ['john@example.com', 'jane@example.com'] // Filter $filtered = collect([1, 2, 3, 4, 5]) ->filter(fn ($item) => $item > 2); // [3, 4, 5] $rejected = collect([1, 2, 3, 4, 5]) ->reject(fn ($item) => $item > 3); // [1, 2, 3] // Reduce $total = collect([1, 2, 3])->reduce(fn ($carry, $item) => $carry + $item, 0); // 6 // Grouping $grouped = collect([ ['department' => 'Sales', 'name' => 'John'], ['department' => 'Sales', 'name' => 'Jane'], ['department' => 'Marketing', 'name' => 'Bob'], ])->groupBy('department'); // Sorting $sorted = collect([3, 1, 2])->sort()->values(); $sorted = collect($users)->sortBy('name'); $sorted = collect($users)->sortByDesc('created_at'); // First and last $first = collect([1, 2, 3])->first(); $first = collect($users)->first(fn ($user) => $user->active); $last = collect([1, 2, 3])->last(); // Aggregates $sum = collect([1, 2, 3])->sum(); $avg = collect([1, 2, 3])->avg(); $max = collect([1, 2, 3])->max(); $count = collect([1, 2, 3])->count(); // Unique values $unique = collect([1, 1, 2, 2, 3])->unique(); // [1, 2, 3] // Chunk for batching collect($items)->chunk(100)->each(function ($chunk) { // Process 100 items at a time }); // Flatten nested arrays $flat = collect([[1, 2], [3, 4]])->flatten(); // [1, 2, 3, 4] // Combine arrays $combined = collect(['name', 'email'])->combine(['John', 'john@example.com']); // ['name' => 'John', 'email' => 'john@example.com'] // When/Unless conditional $collection->when($condition, function ($collection) { return $collection->filter(...); }); // Lazy collections for large datasets LazyCollection::make(function () { $handle = fopen('large-file.csv', 'r'); while (($line = fgets($handle)) !== false) { yield str_getcsv($line); } })->chunk(1000)->each(function ($lines) { // Process 1000 lines at a time }); ``` ## Artisan Commands Artisan is Laravel's command-line interface included with the framework. It provides helpful commands for development and can be extended with custom commands. ```php argument('user'); $shouldQueue = $this->option('queue'); $users = $userId ? User::where('id', $userId)->get() : User::where('subscribed', true)->get(); if ($users->isEmpty()) { $this->error('No users found!'); return Command::FAILURE; } $this->info("Sending reports to {$users->count()} users..."); $bar = $this->output->createProgressBar($users->count()); $bar->start(); foreach ($users as $user) { if ($shouldQueue) { Mail::to($user)->queue(new WeeklyReport($user)); } else { Mail::to($user)->send(new WeeklyReport($user)); } $bar->advance(); } $bar->finish(); $this->newLine(); $this->info('Reports sent successfully!'); return Command::SUCCESS; } } // Interactive commands class CreateUser extends Command { protected $signature = 'user:create'; public function handle(): void { $name = $this->ask('What is the user\'s name?'); $email = $this->ask('What is the user\'s email?'); $password = $this->secret('What is the password?'); if ($this->confirm('Do you want to make this user an admin?')) { $role = 'admin'; } else { $role = $this->choice('Select a role', ['user', 'editor', 'moderator'], 0); } $user = User::create([ 'name' => $name, 'email' => $email, 'password' => Hash::make($password), 'role' => $role, ]); $this->table( ['ID', 'Name', 'Email', 'Role'], [[$user->id, $user->name, $user->email, $user->role]] ); } } ``` ```bash # Run custom command php artisan report:weekly php artisan report:weekly 1 --queue php artisan user:create # Common Artisan commands php artisan serve # Start development server php artisan migrate # Run database migrations php artisan db:seed # Seed the database php artisan make:model Post -mfc # Create model with migration, factory, controller php artisan make:controller ApiController --api php artisan route:list # List all routes php artisan cache:clear # Clear application cache php artisan config:cache # Cache configuration php artisan queue:work # Process queue jobs php artisan schedule:run # Run scheduled tasks php artisan tinker # Interactive REPL ``` ## Testing Laravel is built with testing in mind. PHPUnit support is included out of the box, and a `phpunit.xml` file is pre-configured. The framework also provides expressive helper methods for testing applications. ```php count(3)->create(); $response = $this->get('/posts'); $response->assertStatus(200) ->assertViewIs('posts.index') ->assertViewHas('posts') ->assertSee($posts->first()->title); } public function test_authenticated_user_can_create_post(): void { $user = User::factory()->create(); $response = $this->actingAs($user) ->post('/posts', [ 'title' => 'Test Post', 'content' => 'This is the content.', ]); $response->assertRedirect('/posts'); $this->assertDatabaseHas('posts', [ 'title' => 'Test Post', 'user_id' => $user->id, ]); } public function test_guest_cannot_create_post(): void { $response = $this->post('/posts', [ 'title' => 'Test Post', ]); $response->assertRedirect('/login'); } public function test_api_returns_posts_as_json(): void { $user = User::factory()->create(); $posts = Post::factory()->count(3)->for($user)->create(); $response = $this->actingAs($user) ->getJson('/api/posts'); $response->assertOk() ->assertJsonCount(3, 'data') ->assertJsonStructure([ 'data' => [ '*' => ['id', 'title', 'content', 'created_at'], ], ]); } public function test_validation_errors_returned(): void { $user = User::factory()->create(); $response = $this->actingAs($user) ->postJson('/api/posts', []); $response->assertStatus(422) ->assertJsonValidationErrors(['title', 'content']); } } // Unit test example namespace Tests\Unit; use App\Services\PricingCalculator; use PHPUnit\Framework\TestCase; class PricingCalculatorTest extends TestCase { public function test_calculates_discount_correctly(): void { $calculator = new PricingCalculator(); $result = $calculator->calculateDiscount(100, 0.2); $this->assertEquals(80, $result); } public function test_throws_exception_for_invalid_discount(): void { $this->expectException(\InvalidArgumentException::class); $calculator = new PricingCalculator(); $calculator->calculateDiscount(100, 1.5); } } ``` ```bash # Run tests php artisan test php artisan test --filter=PostTest php artisan test --parallel php artisan test --coverage ``` ## Summary Laravel Framework provides a comprehensive toolkit for building modern PHP web applications. The framework excels in scenarios requiring rapid development with maintainable code, from simple APIs to complex enterprise applications. Its elegant syntax and extensive feature set make it ideal for building RESTful APIs, traditional server-rendered web applications, single-page application backends, real-time applications with WebSockets, and microservices architectures. The framework's queue system efficiently handles background processing for tasks like email sending, image processing, and data synchronization, while the event system enables loosely coupled architectures that scale well. Integration patterns in Laravel follow a consistent philosophy of convention over configuration while remaining highly extensible. The service container serves as the foundation for dependency injection throughout the framework, making it simple to swap implementations and mock dependencies in tests. Facades provide a static-like interface to services while maintaining testability. The framework integrates seamlessly with frontend tools through Laravel Mix or Vite, supports multiple database systems through a unified query builder, and connects with third-party services via official packages for Stripe, Algolia, Passport (OAuth), Sanctum (API tokens), and many others. For deployment, Laravel applications work well with traditional PHP hosting, containerized environments, and serverless platforms like Laravel Vapor, making it a versatile choice for projects of any scale.