MVC in Laravel – Part 3

* Bug fix

Before continue, please change your config/database.php and change your line 38 to:

Now you have your database with some records that I supposed that you been added, you have a Model and connection to database (SQLite) but you don’t have a Controller and View.

Let’s do that!

Firstly, we need a controller

Now look the file  app/HTTP/Controllers/NewsController.php

When we use –resource parameter in artisan make:controller Laravel creates the needed methods with comments for us.

Well, in this case we only use the index method. So, you can remove the others.

Now we have a controller but, we don’t defined a route and view.

Defining the route

Start by defining the route. Remember, the HTTP Requests are requesting something to application and your application will send something to user, these paths or ways are called as routes and will be defined on your routes/web.php

In routes/web.php we need to add a Route to listen verb GET and search for a path and associates it to a controller, how we do that? simple add it to your route/web.php file .

Now when some one request for /news path, the application defines that route is associated to NewsController AT index method.

Use php bult-in server to test it

Well, if you visit your you don’t see any error, however you can see that a blank page was returned to us. We need the news not a blank page. Relax, it’s because we don’t returned any view or response.

But, how we could get ALL the News from your database and pass it to a view ?

Simple, the model has a static method called all!!! 🙂

For a while your controller may be like it

Now you can see something similar to it at the page.


The dd function dumps the given variables and ends execution of the script:

That’s cool, but we still need to pass it to a view!

Create the news.index view

Create a new file resources/views/news/index.blade.php

Note .blade.php means that it is a view and will use the Blade. Blade is the default template engine of Laravel.

Remember in controller you can use the helper view(). The first argument is the name of view but you don’t need to specifies the full extension if you’re using the standards. Simple use view(‘news.index’) the function will understand that you are looking for folder news and view index.blade.php.

Are many ways to pass data to your views, but we will see it after. For now you can use a second argument of function, it receives a array of your data.

Here’s your final NewsController.php

After it, your view receives the $news with the collection that we saw before.

Here’s your news/index.blade.php view file

Note, the @foreach and @endforeach are directives of Blade.


Well, is it. It’s done, now you understand how Laravel applies the MVC.

Other parts of it demonstration

Share this!

No Comments

You can leave the first : )

Leave a Reply

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