Eloquent: Generating Model Classes is a process for generating model classes for interacting with database tables in Laravel. Using Eloquent ORM (Object-Relational Mapper) you can easily read, create, update and delete data from database tables.
The model class is created using Laravel's artisan CLI. Run the following command:
php artisan make:model ModelName
For example, to create a model named Post:
php artisan make:model Post
This will create a Post.php file in the app/Models directory.
model should generally look like this:
namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Post extends Model { use HasFactory; }
Use the following command to create the model and database migration together:
php artisan make:model Post -m
This will create two things:
To build models with Factory and Seeder files:
php artisan make:model ModelName
Laravel assumes the database table name according to the model class name.
For example:
If you want to use custom tables, set the $table property on the model:
php artisan make:model Post
$fillable or $guarded is used to determine which fields in the database can insert data.
namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Post extends Model { use HasFactory; }
php artisan make:model Post -m
If the primary key of your table is something other than id:
php artisan make:model Post -mfsc
Laravel uses table created_at and updated_at columns by default. If you don't want to use them:
class Post extends Model { protected $table = 'blog_posts'; }
Models can be linked to each other using Eloquent relationships.
php artisan make:model ModelName
php artisan make:model Post
namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Post extends Model { use HasFactory; }
The above is the detailed content of Laravel Eloquent ORM in Bangla Part-enerating Model Classes). For more information, please follow other related articles on the PHP Chinese website!