Explain MVC architecture in Laravel.

MVC stands for Model–View–Controller, an architectural pattern that Laravel follows to organize application code into three separate layers. This separation makes the application more structured, maintainable, and scalable.

1. Model

  • Represents the data and business logic.
  • Interacts with the database using Laravel’s Eloquent ORM.

Example:

class User extends Model {
    protected $fillable = ['name', 'email', 'password'];
}

2. View

  • Responsible for the presentation layer (what the user sees).
  • Uses Laravel’s Blade templating engine to display dynamic content.

Example:

<h1>Welcome, {{ $user->name }}</h1>

3. Controller

  • Acts as the middleman between the Model and View.
  • Receives requests, processes data via the Model, and returns a View.

Example:

class UserController extends Controller {
public function index() {
$users = User::all();
return view('users.index', compact('users'));
}
}

Flow of MVC in Laravel

User sends a request (e.g., visit /users).

Route directs the request to the Controller.

Controller fetches data from the Model.

View presents the data to the user.


Comments