Laravel Cheatsheet

1. Installation & Setup

composer create-project --prefer-dist laravel/laravel project-name

// .env configuration
APP_NAME=LaravelApp
APP_URL=http://localhost
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

// Artisan Commands
php artisan serve // Start development server
php artisan migrate // Run migrations

2. Routing

// Basic Route
Route::get('/welcome', function () {
  return 'Welcome to Laravel!';
});

// Route with Parameters
Route::get('/user/{id}', function ($id) {
  return 'User ' . $id;
});

// Named Route
Route::get('/profile', [UserController::class, 'profile'])->name('profile');

// Redirect Route
Route::redirect('/here', '/there');

// Route Grouping
Route::group(['middleware' => ['auth']], function () {
  Route::get('/dashboard', [DashboardController::class, 'index']);
});

3. Controllers

// Basic Controller
php artisan make:controller UserController

// Using Controller
Route::get('/users', [UserController::class, 'index']);

// Resource Controller
php artisan make:controller PostController --resource
Route::resource('posts', PostController::class);

// Dependency Injection in Controller
public function store(Request $request) {
  $validated = $request->validate([ 'title' => 'required|max:255' ]);
}

4. Blade Templating

// Basic Blade Syntax
<h1>{{ $title }}</h1>

// Blade If Statement
@if ($user)
  Welcome, {{ $user->name }}
@else
  Please log in
@endif

// Blade Loop
@foreach ($users as $user)
  <p>{{ $user->name }}</p>
@endforeach

// Blade Includes
@include('partials.header')

// Blade Layouts
@extends('layouts.app')
@section('content')
  <h1>Dashboard</h1>
@endsection

5. Models & Eloquent ORM

// Creating a Model
php artisan make:model User

// Basic Eloquent Queries
$users = User::all();
$user = User::find(1);
$users = User::where('status', 'active')->get();

// Eloquent Relationships
class User extends Model {
  public function posts() {
    return $this->hasMany(Post::class);
  }
}

// Eloquent Create & Update
$user = new User();
$user->name = 'John Doe';
$user->save();

$user = User::find(1);
$user->update(['name' => 'Jane Doe']);

// Eloquent Delete
User::destroy(1);

6. Migrations

// Create a Migration
php artisan make:migration create_users_table

// Running Migrations
php artisan migrate

// Rolling Back Migrations
php artisan migrate:rollback

// Migration Structure
Schema::create('users', function (Blueprint $table) {
  $table->id();
  $table->string('name');
  $table->string('email')->unique();
  $table->timestamps();
});

// Altering Table
Schema::table('users', function (Blueprint $table) {
  $table->string('address')->nullable();
});

7. Middleware

// Creating Middleware
php artisan make:middleware AuthMiddleware

// Applying Middleware to Routes
Route::get('/dashboard', [DashboardController::class, 'index'])->middleware('auth');

// Middleware Handle Method
public function handle($request, Closure $next) {
  if (!auth()->check()) {
    return redirect('login');
  }
  return $next($request);
}

// Middleware Grouping
Route::middleware(['auth', 'admin'])->group(function () {
  Route::get('/admin', [AdminController::class, 'index']);
});

8. Authentication

// Authentication Setup
composer require laravel/ui
php artisan ui vue --auth
php artisan migrate

// Login Route
Route::post('/login', [LoginController::class, 'login']);

// Logout Route
Route::post('/logout', [LoginController::class, 'logout']);

// Register Route
Route::post('/register', [RegisterController::class, 'register']);

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

9. Validation

// Basic Validation
$request->validate([
  'title' => 'required|max:255',
  'email' => 'required|email',
]);

// Custom Validation Messages
$request->validate([
  'title' => 'required',
], [
  'title.required' => 'A title is required',
]);

// Form Request Validation
php artisan make:request StorePostRequest

public function rules() {
  return [
    'title' => 'required',
    'content' => 'required',
  ];
}

10. File Uploads

// File Upload
$request->file('avatar')->store('avatars');

// Store File with Custom Name
$request->file('avatar')->storeAs('avatars', 'custom_name.jpg');

// File Validation
$request->validate([
  'avatar' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
]);

11. API Development

// Creating API Resource Routes
Route::apiResource('users', UserController::class);

// Basic API Response
return response()->json(['message' => 'Success']);

// API Request Validation
public function store(Request $request) {
  $request->validate([
    'name' => 'required|string|max:255',
    'email' => 'required|email|unique:users',
  ]);
}

// API Authentication with Sanctum
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate

// Protecting Routes with Sanctum
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
  return $request->user();
});

12. Queues & Jobs

// Create a Job
php artisan make:job SendEmailJob

// Dispatching a Job
SendEmailJob::dispatch($user);

// Queue Configuration in .env
QUEUE_CONNECTION=database

// Running the Queue Worker
php artisan queue:work

// Queue Retry
php artisan queue:retry all

13. Events & Listeners

// Create an Event
php artisan make:event UserRegistered

// Create a Listener
php artisan make:listener SendWelcomeEmail

// Event-Service Provider Registration
protected $listen = [
  'App\Events\UserRegistered' => [
    'App\Listeners\SendWelcomeEmail',
  ],
];

// Dispatching Events
UserRegistered::dispatch($user);

14. Testing

// Basic Test
php artisan make:test UserTest

// Running Tests
php artisan test

// Test Example
public function testBasicExample() {
  $response = $this->get('/');
  $response->assertStatus(200);
}

// Database Testing
use Illuminate\Foundation\Testing\RefreshDatabase;

class ExampleTest extends TestCase {
  use RefreshDatabase;

  public function testDatabase() {
    User::factory()->create();
    $this->assertDatabaseHas('users', [
      'name' => 'John Doe',
    ]);
  }
}

15. Artisan Console

// Listing Artisan Commands
php artisan list

// Custom Artisan Command
php artisan make:command SendEmails

// Running Custom Command
php artisan send:emails