Laravel 5.4 #3 : Controllers, views, models and migrations

In this post, what we are going to do is connect Laravel to the database, create a model and use it and show the query results in the views.

Create database with PHPMyAdmin

Create a database with PHPMyAdmin is so simple. Simply, we have to access to localhost/phpmyadmin and go to New button on the left sidebar. This will take us to another page, we fill the name of our database and press create. In my case, I named it blog.

 

Connect Laravel with our database

We have to open the file .env it is in the project root and edit from line 8. In my case, will be like this:

 

Create first model

Since we’re going to take advantage of the controller we created earlier, I’m going to create a Post model. You can create it manually or by the command line, I will create it by the command line.

Let’s go to the root of our project and execute this command, what it will do is create the model and its migration file. If we don’t want the migration file, remove -m:

 

Migrations

Migrations are very useful, since they allow you to create the structure of tables and columns of the database without having to touch a single line of SQL. Simply by running a command.

Let’s create the migration for the posts table.

In this link you can find all types of fields that Laravel allows.

To run it:

If everything is fine, we will get a message saying that they are already created.

We add data by hand in the table posts from PHPMyAdmin.

 

Show database data in the view

Open the controller PostsController.php and we are going to edit it.

We have added a new method that takes all the posts in the database. The other simply gets one from the id, if it doesn’t exist, it returns a 404 error. This is thanks to Laravel’s ORM, Eloquent. We will go deeper into it later.

Also we have to add the new route.

And the views:

And we are showing all the existing posts in the database if we access to localhost:8000/posts .

In the next post, we will see how to create content from a form and validate this data, so that it is saved in the database what we want.