RastcodeS

Where we take good care of both your front and back-end needs

Great place to take your code to the next level

Checkout my work and get in touch



RastcodeS Logo
Go Back

Laravel Database and MVC - How I made this app Part VI


Artisan Laravel MySQL PHP



Written by Rastko

date - 06/Sep/18 | views - 1854

Laravel Database and MVC - How I made this app Part VI

     Manipulating databases with Laravel, creating tables and migrations.

     This is the sixth chapter in the - How i made this app series. Check out the others:

 

Creating a Database

 

     We're finished with the static pages for now. It's time to start adding completely dynamic content from the database. We'll use the database later on to manipulate our posts, categories, tags, etc.

     If you have experience with relational databases, you might recall the tedious work it took to manage them. Don't worry about it, we're about to make things a lot simpler.

     To start, we're going to create a new database using PHP MyAdmin. To access this tool, first make sure XAMPP is running. In the browser search field type in:

http://localhost/phpmyadmin/

 

     The interface is very clear to understand. On the right hand side is a list of databases. We'll click on New above the list. Here, we'll add the database name. I'll call mine yourappname. To finish, click "Create".  That's all we needed to do inside PHP MyAdmin. At least for now. We have our brand new MySql database, which is empty for now.


 

Setting up the Environment

 

     Ok, we've created our database and now we need to allow our application to connect to it. For this, we need to edit the .env file at the root of our program:

DB_DATABASE=yourappname
DB_USERNAME=username
DB_PASSWORD=password

 

     Make sure you edit these three lines to match your credentials. Or, if you haven't set up a user, you can add "root" as username and leave the password blank. That's all we needed to do, to let our app connect to the database.


 

Resource Controller

 

     Remember when we created the PagesController in one of the previous chapters? We had to manually write all the function's declaration. Our new PostsController we'll have at least 7 functions. Writing all those declarations would be tedious. Luckily, artisan has a great command to help us out:

php artisan make:controller PostsController --resource

 

     Artisan has created our first resource controller. This type of controller let's us handle our CRUD operations with ease. For anyone, who doesn't know what CRUD acronym stands for:

  • C - Create new items

  • R - Read or get items

  • U - Update existing items

  • D - Delete items

 

     Let's take a look at the actual file inside the Controllers folder. Here you'll find 7 functions. We'll soon be developing them, for now let's check out what they're supposed to do:

  1. index - Here we'll return a list of our posts

  2. create - We show the form for creating a new post (not storing in)

  3. store - Here we actually save to the database

  4. show - Display a single post

  5. edit - Show the form for editing an existing post

  6. update - Handle update of a post

  7. delete - Delete the post from database

 

     We'll develop these in further chapters. For now, let's add the routes to the web.php file. Again, we would usually need to create 7 different routes to handle each call. Laravel team predicted this and we have a helpful function to shorten the work:

// Post Routes
Route::resource('posts', 'PostsController');

 

     The resource function handles all 7 of our posts calls. To test if they work, let's edit the index function to return some text:

public function index()
{
   return "Hello Resource Controller";
}

 

     To call the index function, in the browser type:

http://yourappname.me/posts

 

     You should be seeing the expected text. Later, when we start developing our functions, they'll actually return views.


 

Model and Migration

 

     We've been dealing with 2 of the 3 main parts of an MVC framework. Now it's time to check out the Model. Model stands between the Controller and the View. It's often said, Controllers manipulate the Models, while these models update the Views.  What does it mean? Well explore the cycle of a single MVC call:

     The User lands on your site and sees a link for the posts. Clicking on this link is where the Controller jumps in. It gets a models, or in our case posts. Then the Controller returns this list with a specific view. Finally, the list of posts updates the view to show them on the requested page.

     The previous paragraph has probably given you a hint at what our first model is going to be. Artisan of course has a helpful command to create a new model, but it also has a special flag - -m. This special flag also adds a migration for the database. What are migrations? We've used Git and Git hub to allow us to have the version control capabilities. Migrations are a similar thing for the database. In Laravel, they allow us to declare new tables and edit them. They also handle the behavior for removing a table. The artisan command we're going to use goes like this:

$ php artisan make:model Post -m

 

     The command has created two files - Post.php in the app folder and a migration file in the database - migrations directory. We already have a couple of other migrations. We'll talk about these when we add the security capabilities.

     Most MVC frameworks we'll make you declare each individual field the model is going to use. This is not the case with Laravel, so we can leave the model file for now. We will come back to it later though.

     As for the migration file ending with create_posts_table.php, you can see we already have some useful code:

public function up()
{
   Schema::create('posts', function (Blueprint $table) {
      $table->increments('id');
      $table->timestamps();
   });
}

 

      The up function creates a new table called posts. It also adds 3 fields by default. The id field is our integer identifier. The other two are handled with the timestamps function. This function creats a couple of dates - created_at and updated_at, which are self explanatory. We'll add a couple of other fields:

Schema::create('posts', function (Blueprint $table) {
   $table->increments('id');
   $table->string('title');
   $table->text('content');
   $table->timestamps();
});

 

     We added the title of type string and content of type text. That's all we need for now. Later, when we start adding images and dealing with view counters, we'll come back to it.

     Now it's time to migrate - add our new table to the database. Before we do that, we're going to handle a small bug, which might creep up on you. This bug has to do with default sizes for a string type. To fix it, go to app - Providers - AppServiceProvider.php file. We'll add one line at the top and one inside the boot function, so it ends up looking like this:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // To prevent a database bug
        Schema::defaultStringLength(191);
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

 

     The top line tells the service provider, we'll be using the Schema class. The line inside the boot function sets the default length for a string or a varchar type.

     Note - you can edit this later inside the PHP MyAdmin, and also you might not even need to do this depending on when you're reading this.

     Finally, it's time to migrate. You guessed it, we'll use artisan again. Make sure you've saved everything before running:

php artisan migrate

 

      If you open your database with PHP MyAdmin you'll see our new tables. Most importantly our posts table.


 

Save to GitHub

 

     As always, we'll finish up by pushing our code to GitHub.

Add changes:

git add *

 

Make a commit:

git commit -m "Added PostsController, Post model and a database migration"

 

Push to GitHub:

git push

 

     The code for this project is at github.com/RastkoSavic

     We've reached the end of this chapter. Next, we'll start developing our controller. See you then.


View App/Backend
Login to comment

Comments


No Comments yet. Be the first!

Currently working on a Laravel project

Check it out
Java Break - Declare and Initialize Variables - Java Core Part - VI
Java Break - Declare and Initialize Variables - Java Core Part - VI

     Declaring and initializing variable in Java. How to do it properly and avoid mistakes.

     The sixth chapter...

Java


Recents


Popular