Understanding MVC in Laravel: A Comprehensive Guide - Day 3 Lecture Notes
Understanding MVC in Laravel
A Comprehensive Guide - Day 3 Lecture Notes
Objective:
By the end of this session, students will understand the Model-View-Controller
(MVC) design pattern in Laravel. They will be able to identify the roles of
Models, Views, and Controllers in a Laravel application and create a simple
controller using Laravel's Artisan command.
What is
MVC?
MVC stands for Model-View-Controller,
a software architectural pattern used for developing web applications. It
separates the application into three main components, each with a distinct
role:
1. Model –
Represents the data and the logic of the application.
2. View –
Handles the display (user interface), usually in the form of HTML, CSS, and
JavaScript.
3. Controller –
Contains the logic that connects the Model and View, handling user input and
interactions.
Why use
MVC?
The MVC pattern helps organize
code in a way that is easy to maintain, test, and scale. It separates the
concerns of the application:
- Model manages
the business logic and database interaction.
- View
handles the presentation and UI.
- Controller
serves as a mediator between the Model and the View, handling requests and
controlling the flow of data.
Roles of
MVC Components in Laravel
1. Model
- The Model
in Laravel represents the data structure of the application, typically
interacting with the database. It contains the application's business
logic, database queries, and validation rules.
- Role
of Model:
- It
manages the data (retrieves, stores, and updates it in the database).
- It
often includes methods for interacting with specific tables or performing
operations (CRUD - Create, Read, Update, Delete).
- Creating
a Model: You can create a model using the Artisan
command like this:
php artisan make:model Post
This will generate a model file
located in the app/Models/Post.php file.
- Example
of a Simple Model (Post.php):
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = ['title', 'body']; //
Define the columns we can insert data into
}
2. View
- The View
is responsible for presenting data to the user in a readable and
interactive format. In Laravel, views are generally written in Blade,
a simple and powerful templating engine that allows you to mix HTML with
PHP logic.
- Role
of View:
- It
manages the UI components like forms, buttons, images, and text.
- It
is responsible for the layout and display of data passed from the Controller.
- Creating
a View: Views are stored in the resources/views
directory. For example, creating a post.blade.php file to display a post's
title and body might look like this:
<!DOCTYPE html>
<html
lang="en">
<head>
<meta charset="UTF-8">
<title>Post</title>
</head>
<body>
<h1>{{ $post->title }}</h1>
<p>{{ $post->body }}</p>
</body>
</html>
- Passing
Data from Controller to View: In Laravel, you can pass
data to a view using the with method:
public function show($id)
{
$post = Post::find($id);
return view('post')->with('post', $post);
}
3. Controller
- The Controller
is the intermediary between the Model and the View. It handles the logic
of retrieving data from the Model and passing it to the View. The
Controller also processes user input (like form submissions), performs
necessary operations on the data, and redirects the user accordingly.
- Role
of Controller:
- It
defines how the application responds to user requests.
- It
processes data from the user (forms, URL inputs, etc.) and interacts with
the Model to fetch or update the data.
- It
decides which View should be shown and passes necessary data to it.
- Creating
a Controller: You can create a new controller using the
Artisan command:
php artisan make:controller ExampleController
This creates a controller file in
app/Http/Controllers/ExampleController.php.
- Example
of a Simple Controller (ExampleController.php):
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class ExampleController extends Controller
{
// Method to show a post by ID
public function show($id)
{
$post = Post::find($id); // Fetch the
post from the database
return view('post')->with('post', $post);
// Return view with the post data
}
}
In this example, the show method
fetches a specific post from the Post model and passes it to the post view.
How MVC
Works Together in Laravel
1. The
Request: A user sends a request to the Laravel application, typically through
the browser (e.g., by visiting a URL).
2. Routing: Laravel
routes the request to a specific Controller method (defined in routes/web.php).
3. Controller: The
Controller handles the request, interacts with the Model (to fetch or update
data), and then returns a response (usually a View).
4. Model: If
necessary, the Model retrieves or updates data from the database, which is then
passed to the View.
5. View: The
View displays the data to the user in a readable format (HTML).
Creating
a Controller with Artisan Command
- Step
1: Open the terminal (command line interface).
- Step
2: Run the following command to create a
controller:
php artisan make:controller ExampleController
- Step
3: This command will create a controller in the app/Http/Controllers
directory. Open the ExampleController.php file and add methods to handle
requests.
Example:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ExampleController extends Controller
{
public function index()
{
return "Hello from
ExampleController";
}
}
- Step
4: Define a route in routes/web.php to link a
URL to this controller method:
use App\Http\Controllers\ExampleController;
Route::get('/example', [ExampleController::class, 'index']);
- Step
5: Visit http://your-app-url/example to see the
response from the controller.
Summary
of Key Points
- Model:
Manages data, interacts with the database, and performs business logic.
- View:
Handles the display and UI using Blade templates.
- Controller:
Contains logic that connects Models and Views and processes user input.
Exercise for Students
1. Create a
controller called PostController.
2. Create a
model called Post with fields title and body.
3. Create a
view to display a post's title and body.
4. Define
routes to display a post by its ID.

Comments
Post a Comment