Laravel and the MVC framework
Exam notes on MVC architecture, Laravel routing, controllers, models and views.
Source: laravel_notes.docx — course material by Kiran V.K., published here so it is readable without a Google account.
MVC Architecture Overview
- MVC (Model-View-Controller) is a software design pattern for implementing user interfaces. It divides the application into three interconnected components to separate internal representations of information from the ways information is presented to and accepted from the user.
- Model: Represents the data and business logic. It's responsible for retrieving data from the database, manipulating it, and sending it back to the database or to the View.
- View: Represents the UI. It displays data from the Model to the user and sends user commands to the Controller.
- Controller: Acts as an interface between Model and View. It receives user inputs and decides what to do with them.
Laravel Overview
Laravel is a web application framework with expressive, elegant syntax. It provides a rich set of functionalities that incorporates many features of MVC. Laravel aims to make development tasks easier by reducing common tasks used in most web projects, such as routing, templating, caching, and authentication.
Laravel MVC Framework
- In Laravel, the MVC pattern is implemented as follows:
- Models are typically located in the 'app/Models' directory and represent the application's data.
- Views are located in the 'resources/views' directory and are responsible for presenting data to the user.
- Controllers are located in the 'app/Http/Controllers' directory. They handle user requests, process data using models, and return a response.
Resource Controllers in Laravel
A resource controller in Laravel is a special controller that handles all HTTP requests for a specific resource (like articles, profiles) following RESTful conventions. It provides methods for CRUD operations: create, read, update, delete, and more.
Laravel's Routing Mechanisms
Routing in Laravel deals with directing HTTP requests to their appropriate controllers. Routes are defined in the 'routes' folder. Laravel supports basic routing, route parameters, named routes, middleware, and resource controllers.
Understanding Routes, Controllers, and Models in Laravel
Routes in Laravel
Routes are the invocation URLs that users interact with. Defined in the routes files (such as web.php), they serve as the entry points for HTTP requests. Each route is mapped to a specific controller action, determining which controller method is executed for a given URL.
Example: A route definition in web.php
php
Route::get('/posts', 'PostController@index');This defines a route for '/posts' that is handled by the 'index' method of 'PostController'.
Route::get('/posts/{post}', 'PostController@show');
displays a single post based on its ID.
Controllers in Laravel
Controllers contain the application's logic. They are responsible for processing user requests, interacting with model classes for data handling, and preparing responses. This response could be a rendered view, a JSON response, a redirect, or other types of HTTP responses.
Example: A controller method in PostController
php
class PostController extends Controller
{
public function index()
{
$posts = Post::all();
return view('posts.index', compact('posts'));
}
}Model Classes in Laravel
Models represent the application's data and are directly mapped to database tables, typically with one model class per table. Using Eloquent, Laravel’s ORM, models simplify database interactions through an object-oriented approach. They also encapsulate business logic related to data, such as validation and relationships.
Understanding Eloquent ORM Model-to-Table Mapping in Laravel
Naming Convention
php
By default, Eloquent uses a naming convention to determine the database table associated with a model. For a model named 'Post', it assumes the database table is named 'posts'. This is based on the simple pluralization of the model name.
Example of Custom Table Name:
class Post extends Model
{
protected $table = 'my_custom_posts';
}
In this example, Eloquent will use 'my_custom_posts' as the table associated with the 'Post' model.Primary Key
php
Eloquent assumes each table has a primary key column named 'id'. If your table uses a different column name or type for its primary key, you can define it in your model.
Example of Custom Primary Key:
protected $primaryKey = 'post_id';This tells Eloquent to use 'post_id' as the primary key for the 'Post' model.
Timestamps
php
By default, Eloquent expects 'created_at' and 'updated_at' timestamp columns in your table. If your table doesn't have these timestamp columns, you can disable this feature.
Example of Disabling Timestamps:
public $timestamps = false;Model Properties and Methods
Models in Laravel can define relationships, scopes, accessors, mutators, and more. Example of a Basic Eloquent Model:
class Post extends Model
php
{
protected $table = 'posts';
protected $primaryKey = 'post_id';
public $timestamps = false;
}This model is set up to interact with a database table named 'posts', with a custom primary key and no automatic timestamp management.
Route Model Binding in Laravel
- Route Model Binding simplifies the process of passing parameters from routes to controllers. It automatically injects model instances into routes.
- Implicit Binding: Laravel automatically resolves Eloquent models using the ID in the route.
- Explicit Binding: Developers can define custom logic to resolve model instances.
Creating & Rendering Views
Views in Laravel are created using the Blade templating engine, stored in the 'resources/views' directory. Blade allows you to embed PHP code in HTML templates, making it dynamic and interactive.
Passing Data to Views
Data can be passed to views using several methods, including with, compact, or directly as an array. Controllers typically handle data passing.
Sharing Data with All Views
Data can be shared across all views using view composers or view shares, useful for data required in multiple views like user information, settings, etc.
Example Use Case
- Consider a blog application with a 'Post' model, 'PostController', and views for displaying posts.
- Model: 'Post' represents the blog posts in the database.
- Controller: 'PostController' handles requests for listing all posts (
index) and showing a specific post (show). - Views: 'index.blade.php' lists all posts. 'show.blade.php' displays a single post.
- Route Model Binding: The 'show' route uses implicit binding to fetch the specific 'Post' instance.
Example: Basic Route Definition
Route::get('/posts', 'PostController@index'); Route::get('/posts/{post}', 'PostController@show'); This example shows two routes. The first route displays all posts, and the second displays a single post based on its ID.
Example: PostController Methods
// PostController
php
public function index()
{
$posts = Post::all();
return view('posts.index', compact('posts'));
}
public function show(Post $post)
{
return view('posts.show', compact('post'));
}These methods in PostController handle requests to list all posts (index) and to show a specific post (show). The show method uses route model binding.
Example: Blade View for Listing Posts
{{-- resources/views/posts/index.blade.php --}}
php
@extends('layouts.app')
@section('content')
<h1>All Posts</h1>
<ul>
@foreach ($posts as $post)
<li>
<a href="{{ route('posts.show', $post->id) }}">
{{ $post->title }}
</a>
</li>
@endforeach
</ul>
@endsectionThis Blade view (index.blade.php) lists all blog posts. Each post title links to its detailed view.
Example: Blade View for Showing a Post
{{-- resources/views/posts/show.blade.php --}}
php
@extends('layouts.app')
@section('content')
<h1>{{ $post->title }}</h1>
<p>{{ $post->content }}</p>
<a href="{{ route('posts.index') }}">Back to All Posts</a>
@endsectionThis Blade view (show.blade.php) displays the details of a single blog post.
Importance of Route Model Binding
- Route Model Binding in Laravel simplifies the retrieval of model instances in routes, enhancing code readability and efficiency. It automatically injects the correct model instance based on the route parameter, reducing the need for manual retrieval and validation.
- Reduces Boilerplate: Eliminates repetitive code for querying models.
- Increases Safety: Automatically handles 'not found' cases, making routes more robust.
- Enhances Readability: Makes controller methods cleaner and more expressive.
- Improves Efficiency: Streamlines the process of linking route parameters to model instances.
Importance of Controller
- Controllers in Laravel are tasked with handling user requests, leveraging models to interact with data, and returning responses (often as views). They are the bridge between the frontend and the backend.
- Logical Grouping: Controllers group related request handling logic, making the application organized.
- Separation of Concerns: By isolating the request handling from the UI (views) and data management (models), controllers promote a clean architecture.
- Reusability: Controllers can be reused across different parts of the application, reducing code duplication.
- Testability: Isolating logic in controllers makes the application more testable.
Example: In our use case, PostController has methods like index and show, where index retrieves and displays all posts, while show deals with displaying a specific post.
Views in Laravel
- Views in Laravel, created using the Blade templating engine, are responsible for presenting data to the user. They are an essential part of the MVC architecture, representing the application's user interface.
- Blade Templating: Blade allows for dynamic content rendering, control structures, and template inheritance, leading to more maintainable and reusable code.
- Data Passing: Controllers pass data to views, which then render this data. This separation ensures that the view only deals with the presentation logic.
- Example: The
index.blade.phpview in our blog application lists all posts, whileshow.blade.phpdisplays details of a single post, both receiving data from thePostController.
Passing Data to Views
- Passing data to views is a critical aspect of Laravel's MVC architecture. It allows the separation of logic (controller) and presentation (view), enabling dynamic content rendering.
- Methods: Data can be passed using various methods like
with,compact, or directly as an array. - Scope: Data passed to views is only available in that view, promoting encapsulation and preventing data leakage.
- Example: In
PostController, theindexmethod usescompactto pass the$postsvariable to theindexview, where it's used to display a list of posts.
Sharing Data with All Views
- Sharing data across all views is useful for data that is required globally, like user profiles, settings, or notifications.
- View Composers: Laravel allows the sharing of data using view composers, which bind data to views every time they are rendered.
- Global Availability: This ensures that certain data is consistently available in all views, enhancing usability and reducing redundancy.
- Example: A common use case is sharing user authentication status or user profiles in the main layout, making it accessible in all views.