Laravel : Create Model with Migration, Controller and generate DB Table

 

Laravel: Create Model with Migration, Controller and generate DB Table


Laravel makes it very easy to create a new Model, Model is the M part of the MVC architecture, It is basically a PHP class that maps to a particular database table and is useful in running Eloquent functions as well.

Create new Model

Consider you decided to build a Blog Application in Laravel, and as every blog application has Posted. You decided your first model to be Post. To generate a Post model in your application, Open your Terminal / Command Prompt and navigate to the project root.

Run the following command

php artisan make:model Post -mr

Once this command is executed, open your editor.

Notice that a new Post.php model is created in your project under App directory

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    //
}

Also notice a new migration file is created under the folder database > migrations

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

And, also a new resourceful Controller is generated under the directory App > Http > Controllers

<?php

namespace App\Http\Controllers;

use App\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
..
..
}

Generate Database Table

Since we are ready with our first Model, Let’s go ahead and modify the migration file to add columns in our posts table.

To add some fields, Posts are supposed to have a title and a body. Let’s add these fields to our migrations file.

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

Great, we are now ready to generate the Posts table from our migration file.

Go to your terminal and generate the following command.

php artisan migrate

There you go! You now know how to create a model in Laravel and also how to create a corresponding database table corresponding to the Model.

Reactions

Post a Comment

0 Comments