Lavarel‐ Chapters 5 to 10 - pierre-akhrass/Lavarel-Docs GitHub Wiki
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.
Use the Artisan command:
php artisan make:controller -r Dashboard/PostController -m Post
This will:
- Create a
PostController
inside theDashboard
namespace. - Generate resource methods:
index
,create
,store
,show
,edit
,update
,destroy
. - Link the controller to the
Post
model automatically.
app/
├── Http/
│ ├── Controllers/
│ │ └── Dashboard/
│ │ └── PostController.php
├── Models/
│ └── Post.php
resources/
└── views/
└── post/
├── index.blade.php
├── create.blade.php
├── edit.blade.php
-
Define Routes in
routes/web.php
:
Route::resource('post', PostController::class);
-
Create Controller using
php artisan make:controller -r
. -
Design Views for each CRUD operation (
index
,create
,edit
,show
). - 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'
];
}
- 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');
}
- Paginate and List Items:
$posts = Post::paginate(10);
return view('post.index', compact('posts'));
- 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
- 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();
- 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']);
Route::get('/home', [HomeController::class, 'index'])->name('home');
Use in views:
<a href="{{ route('home') }}">Home</a>
Route::get('/user/{id}', function($id) {
return "User ID is $id";
});
Route::get('/user/{name?}', function($name = 'Guest') {
return "Hello $name";
});
Route::middleware(['auth'])->prefix('admin')->group(function () {
Route::resource('posts', Admin\PostController::class);
});
- Lightweight starter kit.
- Includes: login, registration, email verification, password resets.
- Built with Blade, TailwindCSS, Alpine.js (optionally Vue or React).
composer require laravel/breeze --dev
php artisan breeze:install
npm install && npm run dev
php artisan migrate
- Automatically registers routes in
routes/web.php
:
Route::get('/dashboard', function () {
return view('dashboard');
})->middleware(['auth'])->name('dashboard');
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);
}
- 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();
- 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();