Create Contact Model and Contacts Table
- Nov 8, 2022
- 2 min read
Updated: Dec 13, 2022
Eloquent ORM: is an object-relational mapper which included by default within the Laravel framework. Eloquent ORM is communicate with database tables and provide an object-oriented approach to CRUD operations. Also through Eloquent ORM it is easy to work with multi database at same time.
When using the Eloquent, each table has corresponding Model to interact and retrieve records from the database. Eloquent model allows the user to store, update, and delete records.
make:model Artisan command is used to create model. After creating the model by default, it lives in the app\Models.
I have used the below command to create contact model and table.
php artisan make:model Contact -m Laravel by default uses the plural name of the class as table name; therefore, in my case Laravel migrated contacts table.
contacts table

I have created the columns for table, used the unsignInteger method for user_id column because it defines the relationship with users table. I have also used the foreign method to reference user_id column with id column on users table.
php artisan migrate – execute migrate artisan command to run outstanding migration.
Contact Model

Laravel mass assignment is a process of sending an array of data that will be saved to the specified model at once. It is a fast and easy-to-use procedure but there is possible security threat behind it. So fillable attribute allows the user to specify which fields is mass-assignable in model, and the guarded is the reverse of fillable.
In Contact model I have used the guarded attribute instead of fillable.
protected $guarded = ['id']; - it means only id field is not mass-assignable, id field is auto increment.
belongsTo method defines child -> parent relationship, this method defines in child (Contact) model. belongsTo is about having one, for about having many there is an other method called blongsToMany().

In one to many relationship there is single model as parent and one or more child models. hasMany method defines in User model to build relationship between Contact model and User model.
Tinker
Tinker help me to interact with entire Laravel project through command line, including eloquent models. Laravel Tinker is a powerful REPL (Read-Evaluate-Print-Loop) for the Laravel framework, powered by the PsySH package.





Comments