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

Create new Model

Consider you decided to build an Blog Application in Laravel, and as every blog application have Posts. 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
  • make:model is an artisan command to create Model file, Notice that it's a good practice to name your model as singular (Post not Posts)
  • -m indicates that we intend to create a migration file for the model as well.
  • -r denotes that we also want a resourceful controller to be created, that goes along with Post model.

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 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 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 in 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 model in Laravel and also how to create a corresponding database table corresponding to the Model.

Comments