Passing Data to Views in Laravel: 3 Simple Methods You Must Know
Learn different ways to pass data from controllers to your Blade views.
MVC stands for Model-View-Controller - a design pattern that separates an application into three main components. This separation makes your code more organized, maintainable, and scalable.
Think of MVC like a restaurant:
Models represent your application's data and business logic. They interact with the database.
// app/Models/User.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
// This model automatically links to the 'users' table
protected $fillable = ['name', 'email', 'password'];
// Business logic example
public function isAdmin()
{
return $this->role === 'admin';
}
}
What Models Do:
Views are what users see - the HTML templates. Laravel uses Blade templating engine.
// resources/views/users/profile.blade.php
<html>
<head>
<title>User Profile</title>
</head>
<body>
<h1>Welcome, {{ $user->name }}!</h1>
<p>Email: {{ $user->email }}</p>
@if($user->isAdmin())
<div class="admin-badge">Administrator</div>
@endif
<ul>
@foreach($user->posts as $post)
<li>{{ $post->title }}</li>
@endforeach
</ul>
</body>
</html>
What Views Do:
Controllers handle user requests, process data using Models, and return Views.
// app/Http/Controllers/UserController.php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function showProfile($userId)
{
// Get data from Model
$user = User::findOrFail($userId);
// Return View with data
return view('users.profile', ['user' => $user]);
}
public function updateProfile(Request $request, $userId)
{
$user = User::findOrFail($userId);
// Process data from request
$user->update([
'name' => $request->input('name'),
'email' => $request->input('email')
]);
return redirect()->route('user.profile', $userId);
}
}
Let's trace a complete user request:
// routes/web.php
Route::get('/profile/{id}', [UserController::class, 'showProfile']);
public function showProfile($id)
{
$user = User::find($id); // Model fetches data
return view('profile', ['user' => $user]); // View displays data
}
// Behind the scenes, this runs: SELECT * FROM users WHERE id = 1
Let's see MVC in action with a blog:
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
public function getExcerpt()
{
return Str::limit($this->content, 100);
}
}
class PostController extends Controller
{
public function index()
{
$posts = Post::with('user')->latest()->get();
return view('posts.index', compact('posts'));
}
public function show(Post $post)
{
return view('posts.show', compact('post'));
}
}
@foreach($posts as $post)
<article>
<h2>{{ $post->title }}</h2>
<p>By: {{ $post->user->name }}</p>
<p>{{ $post->getExcerpt() }}</p>
<a href="/posts/{{ $post->id }}">Read More</a>
</article>
@endforeach
✅ Separation of Concerns
✅ Easier Maintenance
✅ Better Testing
// Test controller logic
public function test_user_can_view_profile()
{
$user = User::factory()->create();
$response = $this->get("/profile/{$user->id}");
$response->assertStatus(200);
}
✅ Code Reusability
1. What is MVC and why is it important?
MVC separates application into Model, View, and Controller components, making code more organized, maintainable, and testable.
2. How does Laravel implement MVC?
Laravel uses Eloquent for Models, Blade for Views, and Controller classes to handle the application logic and coordination.
3. What goes in a Model vs Controller?
Models handle data logic and database interactions. Controllers handle HTTP requests, process data using models, and return responses.
4. Can you explain the request lifecycle in Laravel MVC?
Request → Routes → Controller → Model (database) → Controller → View → Response
5. What are Laravel's conventions for MVC?
Models: app/Models/User.php
Views: resources/views/users/
Controllers: app/Http/Controllers/UserController.php
| Component | Responsibility | Location |
|---|---|---|
| Model | Data & Business Logic | app/Models/ |
| View | Presentation & UI | resources/views/ |
| Controller | Request Handling | app/Http/Controllers/ |
Now you understand the foundation of Laravel! In our next post, we'll dive into Laravel Routing: All You Need to Know About GET, POST, and Resource Routes where you'll learn how to direct traffic in your application.