laravel/framework
Laravel’s core framework code for building modern PHP web apps with elegant syntax. Includes fast routing, a powerful DI container, sessions and caching, database migrations, queues for jobs, and real-time event broadcasting.
## Getting Started
### Minimal Steps
1. **Installation**
```bash
composer create-project laravel/laravel project-name
First Route
Define a route in routes/web.php:
use Illuminate\Http\Request;
Route::get('/greet', function (Request $request) {
return "Hello, {$request->input('name', 'World')}!";
});
php artisan serve and visit http://localhost:8000/greet?name=John.First Controller
php artisan make:controller GreetController
Update routes/web.php:
Route::get('/greet', [GreetController::class, 'index']);
Implement the controller (app/Http/Controllers/GreetController.php):
public function index(Request $request) {
return response()->json(['message' => "Hello, {$request->name}"]);
}
First Migration
php artisan make:migration create_users_table
Define schema in the migration file, then run:
php artisan migrate
First Model
php artisan make:model User -m
-m flag creates a migration for the model.app/ Directory: Core application logic (models, controllers, providers).config/ Directory: Configuration files for services (database, mail, queues, etc.).routes/ Directory: Web, API, console, and channel routes.resources/views/: Blade templates for frontend rendering.database/migrations/: Database schema changes.app/Console/Kernel.php: Command scheduling and queue workers.Create Model & Migration
php artisan make:model Post -mcr
-c creates a controller stub, -r sets up resource routes.Define Migration Schema
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->timestamps();
});
Run Migration
php artisan migrate
Seed Data (Optional)
php artisan make:seeder PostSeeder
Define seed data in database/seeders/PostSeeder.php and run:
php artisan db:seed --class=PostSeeder
Test Routes
/posts to see the auto-generated CRUD routes (index, create, store, etc.).RESTful Resources:
Route::resource('posts', PostController::class);
Route Model Binding:
Route::get('/posts/{post}', [PostController::class, 'show']);
Post model from the {post} parameter.Named Routes:
Route::get('/dashboard', function () {
return redirect()->route('posts.index');
})->name('dashboard');
API Routes:
Route::apiResource('api/posts', PostController::class)->middleware('auth:sanctum');
Basic Queries:
$posts = Post::where('title', 'like', '%Laravel%')->orderBy('created_at', 'desc')->get();
Relationships:
// Model: Post.php
public function user() {
return $this->belongsTo(User::class);
}
// Eager loading
$posts = Post::with('user')->get();
Scopes:
// Model: Post.php
public function scopePublished($query) {
return $query->where('published_at', '<=', now());
}
// Usage
$publishedPosts = Post::published()->get();
Accessors/Mutators:
// Model: Post.php
public function getTitleAttribute($value) {
return ucfirst($value);
}
public function setBodyAttribute($value) {
$this->attributes['body'] = strtolower($value);
}
Global Middleware:
// app/Http/Kernel.php
protected $middleware = [
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
];
Route-Specific Middleware:
Route::get('/admin', function () {
// ...
})->middleware('auth', 'admin');
Custom Middleware:
php artisan make:middleware EnsureUserIsAdmin
// app/Http/Middleware/EnsureUserIsAdmin.php
public function handle(Request $request, Closure $next) {
if (!auth()->user()->isAdmin()) {
abort(403);
}
return $next($request);
}
Form Request Validation:
php artisan make:request StorePostRequest
// app/Http/Requests/StorePostRequest.php
public function rules() {
return [
'title' => 'required|string|max:255',
'body' => 'required|string',
];
}
// Controller
public function store(StorePostRequest $request) {
$validated = $request->validated();
// ...
}
Inline Validation:
$validated = $request->validate([
'title' => 'required|string|max:255',
'body' => 'required|string',
]);
Custom Command:
php artisan make:command SendReportCommand
// app/Console/Commands/SendReportCommand.php
protected $signature = 'report:send {user?}';
protected $description = 'Send a report to the specified user';
public function handle() {
$user = $this->argument('user');
// Logic to send report
}
Scheduling Commands:
// app/Console/Kernel.php
protected function schedule(Schedule $schedule) {
$schedule->command('report:send')->dailyAt('9:00');
}
Dispatching Jobs:
php artisan make:job SendEmailJob
// app/Jobs/SendEmailJob.php
public function handle() {
Mail::to('user@example.com')->send(new OrderShipped($order));
}
// Dispatch job
SendEmailJob::dispatch($order);
Queue Workers:
php artisan queue:work
Custom Event:
php artisan make:event OrderShipped
// app/Events/OrderShipped.php
public function broadcastOn() {
return new PrivateChannel('orders');
}
Listener:
php artisan make:listener SendOrderConfirmation
// app/Listeners/SendOrderConfirmation.php
public function handle(OrderShipped $event) {
// Logic to send confirmation
}
// Register in EventServiceProvider
protected $listen = [
OrderShipped::class => [
SendOrderConfirmation::class,
],
];
HTTP Tests:
public function test_post_creation() {
$response = $this->post('/posts', [
'title' => 'Test Post',
'body' => 'This is a test.',
]);
$response->assertStatus(201);
}
Feature Tests:
public function test_user_can_create_post() {
$user = User::factory()->create();
$response = $this->actingAs($user
How can I help you explore Laravel packages today?