Home » Laravel » How to Create Model in Laravel

How to Create Model in Laravel

Models in Laravel provide a simple interface for interacting with the database. A model can help create a new record in the database and find needed records. But first, you have to create a model class and configure it properly.

In this article we will dive into how to create model in Laravel. We will also explain the meaning of model fields and show how to make a model with migration and controller.

How to Make a Model in Laravel

1. Syntax and Options

Of course, you can create a model class manually using your IDE, but there is a more convenient way. The artisan utility has a make:model command that helps create models. Here is its syntax:

$ php artisan make:model [options] [name]

By default, it creates only a model class, but here are more options. Let’s have a look at them:

  • -c, –controller – create a controller for the model;
  • -f, –factory – create a factory for the model;
  • -m, –migration – create a migration for the model;
  • –policy – create a policy for the model;
  • -s, –seed – create a seeder for the model;
  • -a, –all – create controller, factory, policy, and migration for the model;
  • –test – create PHPUnit test file for the model;
  • –pest – create a Pest test file for the model;
  • -p, –pivot – the model should be a pivot model for a custom intermediate table;
  • –force – create a model even if it already exists.

If you want to create a new controller with the model, here are a few options that can configure the controller characteristics:

  • –api – create an API controller;
  • –R, –requests – create a FromRequest class for the controller;
  • -r, –resource – create a Resource class for the controller;

Before we proceed to examples, let’s deal with the model name. It must be an English word in singular, not plural because Laravel uses the plural form of this word as the table name for the model.

2. Model Creation

Let’s have a look at examples. Run this command to create a new model with the name Article:

php artisan make:model Article

This command will make a class Article in App/Models directory with this code:

namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Article extends Model { use HasFactory; }

Also, you need a migration that will create the table in the database for the model. Use the make:migration command to create migration for the Article model:

php artisan make:migration CreateArticlesTable

The migration name also matters. If you want Laravel to create a migration for a new table use this naming syntax:

  • CreateTableNameTable/create_table_name_table
  • CreateTableName/create_table_name

The migration file from the example will create a file in the database/migrations folder with this code:

use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create("articles", function (Blueprint $table) { $table->id(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists("articles"); } };

You can use camel case or snake case in the name, but I prefer camel case. Laravel automatically converts it to a snake case, so you can use what you want. In this case, Laravel will produce migration with the table creation code.

But if you want to modify an existing table use another syntax:

  • SomethingInTableNameTable/something_in_table_name_table
  • SomethingToTableNameTable/something_to_table_name_table
  • SomethingFromTableNameTable/something_from_table_name_table

The code will look like this:

return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table("articles", function (Blueprint $table) { // }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table("articles", function (Blueprint $table) { // }); } };

If you choose another name, the migration will not contain a template code and table name, you will have to write everything by yourself.

If you want to create a migration with the model, use the -m option:

php artisan make:model -m Article

It will produce the model with the code above, and migration for new table creation like this:

If you need model, migration, factory, seeder, and controller use:

php artisan make:model -mfsc Article

You can use the factory to describe how to create a new model instance, and the seeder to create a required quantity of models.

Don’t forget to migrate all your migrations before using the model. Run the following command to do this:

php artisan migrate

You can find all migrations that are not applied by using this command:

php artisan migrate:status

3. Model Configuration

You can configure the model using Model class fields. Let’s look at their short description:

  • $table – use this table name for the model;
  • $primaryKey – the field that will be used as a primary key, the value of this field should be unique and can help identify any record in the table. By default it is the id field.
  • $keyType – the type of the primary key field. By default it is an integer. But if you want to use a UUID field as the primary key, you should change it to a string.
  • $incrementing – by default Laravel generates the next value for the primary key by incrementing the last value. If you want to create this value manually, set this field to false.
  • $with – contains relationships that should be eagerly preloaded for this model.
  • $attributes – allows setting default values for attributes.
  • $casts – converting attributes to the desired types or classes.
  • $dates – attributes, that should be cast to DateTime.
  • $touches – configures relations that will be updated on the current model update.
  • $timestamps – by default Laravel puts the current timestamp in the created_at and updated_at fields. If you want to disable this feature, set this field to false.
  • $dateFormat – the format, that will be used for date serialization and deserialization.
  • $fillable – configures attributes, that should be bulk assignable. It impacts the fields that will be set using the fill() method.
  • $guarded – configures attributes, that can’t be set using the fill() method or another bulk assign method. By default, it is all fields in the model.
  • $hidden – sets attributes that shouldn’t be serialized using the toArray() method.
  • $visible – sets attributes that can be serialized using the toArray() method.
  • $softDeletes – enables using soft deletion instead of permanent deletion for the model. Requires the deleted_at column in the database.

In most cases, most of these parameters are not required. But if you want to use the fill() method or create a new model from an array of attributes, configure the $fillable field. For example, the Article model has title, content, and author fields. Open the model class file and add them to the $fillable field as shown below:

class Article extends Model { protected $fillable = ["title", "content", "author"]; //... }

Now, you can create the model from an array:

$data = [ "title" => "Test article", "content" => "Text", "author" => "nobody", ]; $article = new Article($data);

Or you can use the fill() method:

$article = new Article(); $article->fill($data);

If you don’t stick to model naming recommendations, Laravel may not be able to determine the table name for the model automatically. In this case, you can specify the table name in the $table field:

class Article extends Model { public $table = "articles"; //.. }

You can set a default value for any attribute using the $attributes field. For example, if you want to set a default value for the author field to ‘Anonymous’, add this code:

protected $attributes = [ 'author' => 'Anonymous', ];

If you don’t want your model to serialize timestamps, you can add created_at and updated_at fields to the $hidden field. For example:

protected $hidden = ["title"];

That’s it.

4. Create a Pivot Model

Pivot tables are used when several elements from one table need to be related to several elements from another table. Generally, these tables contain only two fields identifier of the record from the first table, and the identifier of the record from the second table. Also they do not have a primary key. Technically, you can create a composite primary key on these two fields but at the moment of writing Eloquent does not support composite primary keys. So you can’t use the Illuminate\Database\Eloquent\Model class to create the model for a pivot table. But you can extend your class from Illuminate\Database\Eloquent\Relations\Pivot.

Let’s look at the example. Imagine that you have a model Tag and model Article. Any article can have multiple tags. So, you should use a pivot table. Use this command to create it:

php artisan make:model ArticleHasTag --pivot

The command will generate a class in App/Models with this code:

namespace App\Models; use Illuminate\Database\Eloquent\Relations\Pivot; class ArticleHasTag extends Pivot { // }

You don’t need to change it. But now you can use it in relation descriptions in Article and Tag models instead of a raw table name.

Wrapping Up

In this article, we have explained how to create model in Laravel with migration and how to configure this model. As you can see it is pretty easy. You can

Your Reaction

Leave a Comment