MVC in Laravel

If you didn’t read the previous post about Directory Structure in Laravel, you may be thinking that Laravel have specific folders for each layer in MVC, but isn’t like that.

To try to explain how the MVC works in Laravel we will do little and basic CRUD application together.

Getting started

To understand more about MVC in Laravel, we need to install a fresh installation of Laravel, let’s do it

Only to remember, we are creating a new project ( laravel/laravel ) in folder laravel with default params.

To certify that everything goes right, start server in your terminal with artisan. Type the command below in the laravel folder in your terminal.

The output must be it:

Now the PHP bult-in server is running, visit the http://127.0.0.1:8000 page and see the default installation of Laravel, like below:

MVC in Laravel

See how MVC is implemented in Laravel

Models

By default the Model classes are stored in /app directory, but you can change it, and i recommend it, for example I created /app/Models folder to my models.

Let’s see the default /app/User.php model

You must have noticed that Model classes are extensions of
Illuminate\Database\Eloquent\Model, we will see more about Database and Models in future, but nothing  prevents you of explore it class.

Views

To recap, views are our output (templates) to users and be stored in /resources/views.

Controllers

The controllers are in folder /app/Http/Controllers. It’s important to remember that controllers usually are our links between model and views. A controller is called by Route, and we can say that route is called in any user request, in our case by HTTP requests.

Basic of route, only to understand this example

The web routes are in /routes/web.php

In this example, we don’t have a Controller or Model, as you saw it’s only a route with type get that will be called when users request for the ‘/’ page in browser and it returns a Closure that return a view(‘welcome’);

What’s it????

Simple, the Route facade defines the default page for get requests and return a instance of View, simple like that, how it don’t have data, only will return the file resources/view/welcome.blade.php

To be continued in next post 😉

Share this!




No Comments


You can leave the first : )



Leave a Reply

Your email address will not be published. Required fields are marked *

*