Lavarel‐ Chapters 5 to 10 - pierre-akhrass/Lavarel-Docs GitHub Wiki

Chapter 5: MVC and Introduction to Controllers

Laravel is built on the MVC architectural pattern, which separates the application logic into three interconnected components:

  • Model: Manages the data and business logic. Each model typically maps to a table in the database.
  • View: Responsible for rendering the user interface. In Laravel, views are written using the Blade templating engine.
  • Controller: Handles incoming HTTP requests, manipulates data using models, and returns responses via views.

Creating a Controller with Resource Methods

Use the Artisan command:

php artisan make:controller -r Dashboard/PostController -m Post

This will:

  • Create a PostController inside the Dashboard namespace.
  • Generate resource methods: index, create, store, show, edit, update, destroy.
  • Link the controller to the Post model automatically.

Example Folder Structure

app/
├── Http/
│   ├── Controllers/
│   │   └── Dashboard/
│   │       └── PostController.php
├── Models/
│   └── Post.php
resources/
└── views/
    └── post/
        ├── index.blade.php
        ├── create.blade.php
        ├── edit.blade.php

Chapter 6: Creating a CRUD with MVC

Steps to Implement a CRUD Application

  1. Define Routes in routes/web.php:
Route::resource('post', PostController::class);
  1. Create Controller using php artisan make:controller -r.
  2. Design Views for each CRUD operation (index, create, edit, show).
  3. Use Form Requests to validate input:
php artisan make:request StorePostRequest

In the request class, define validation rules:

public function rules()
{
    return [
        'title' => 'required|string|max:255',
        'content' => 'required'
    ];
}
  1. Use Eloquent in the controller to interact with the database:
public function store(StorePostRequest $request)
{
    Post::create($request->validated());
    return redirect()->route('post.index')->with('status', 'Post created successfully');
}
  1. Paginate and List Items:
$posts = Post::paginate(10);
return view('post.index', compact('posts'));

Chapter 7: Session and Flash Messages

Flash Messages

  • Used to display a message after redirection (e.g., success or error).
return redirect()->route('post.index')->with('status', 'Post created!');

In Blade:

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

Persistent Session Storage

  • Laravel uses session() helper to interact with session data.
// Store
session(['role' => 'admin']);

// Retrieve
$userRole = session('role', 'guest');

// Remove specific item
session()->forget('role');

// Clear all session data
session()->flush();

Chapter 8: Laravel Routing

Types of Routes

  • GET: Read data.
  • POST: Submit data.
  • PUT/PATCH: Update data.
  • DELETE: Remove data.
Route::get('/posts', [PostController::class, 'index']);
Route::post('/posts', [PostController::class, 'store']);
Route::put('/posts/{id}', [PostController::class, 'update']);
Route::delete('/posts/{id}', [PostController::class, 'destroy']);

Named Routes

Route::get('/home', [HomeController::class, 'index'])->name('home');

Use in views:

<a href="{{ route('home') }}">Home</a>

Parameters and Optional Values

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

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

Route Groups and Middleware

Route::middleware(['auth'])->prefix('admin')->group(function () {
    Route::resource('posts', Admin\PostController::class);
});

Chapter 9: Laravel Breeze Authentication

What is Breeze?

  • Lightweight starter kit.
  • Includes: login, registration, email verification, password resets.
  • Built with Blade, TailwindCSS, Alpine.js (optionally Vue or React).

Installation Steps

composer require laravel/breeze --dev
php artisan breeze:install
npm install && npm run dev
php artisan migrate

Routes and Views

  • Automatically registers routes in routes/web.php:
Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware(['auth'])->name('dashboard');

Role-Based Authorization

Add enum column to users table:

$table->enum('rol', ['admin', 'regular'])->default('regular');

Create custom middleware to check roles:

if (auth()->user()->rol !== 'admin') {
    abort(403);
}

Chapter 10: Common Eloquent Operations

Basic Eloquent Methods

  • Retrieve All:
Post::all();
  • Where Condition:
Post::where('title', 'like', '%Laravel%')->get();
  • First or Fail:
Post::findOrFail($id);
  • Create New Record:
Post::create(['title' => 'My Title', 'content' => 'Lorem ipsum']);
  • Update a Record:
$post = Post::find(1);
$post->update(['title' => 'Updated Title']);
  • Delete a Record:
$post = Post::find(1);
$post->delete();

Advanced Queries

  • Ordering and Limits:
Post::orderBy('created_at', 'desc')->take(5)->get();
  • Joins:
DB::table('posts')
    ->join('users', 'posts.user_id', '=', 'users.id')
    ->select('posts.*', 'users.name')
    ->get();
  • Count, Exists, Aggregates:
Post::count();
Post::where('status', 'published')->exists();
  • Random Rows:
Post::inRandomOrder()->take(3)->get();
⚠️ **GitHub.com Fallback** ⚠️