How to define a model in Laravel



Image not found!!

In Laravel, you can define a model to interact with your database tables. Models are used to encapsulate the business logic of your application and provide an object-oriented interface for interacting with the database. Here's a step-by-step guide on how to define a model in Laravel:


1. Create a Model:

Laravel provides an Artisan command to create a new model. Open your terminal and run the following command, replacing YourModelName with the name you want for your model:

php artisan make:model YourModelName

This will create a new file in the app directory with the name YourModelName.php.


2. Define the Model:

Open the generated model file (YourModelName.php) in a text editor, and you'll see a class definition. The class should extend the

Illuminate\Database\Eloquent\Model class. Here's a basic example:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class YourModelName extends Model
{
    // Your model logic goes here
}


3. Set the Table Name (Optional):

By default, Laravel assumes that the table name associated with the model is the plural, snake-cased version of the model's class name. If your table has a different name, you can specify it by adding a $table property to your model:

protected $table = 'your_table_name';


4. Specify the Primary Key (Optional):

If your table's primary key is not named id or if it's not an auto-incrementing integer, you can specify it in your model:

protected $primaryKey = 'your_primary_key';
public $incrementing = false; // If the primary key is not auto-incrementing


5. Define Fillable or Guarded Attributes:

You need to specify which attributes are mass-assignable (fillable) or guarded against mass-assignment. You can do this by adding the $fillable or $guarded property to your model. Fillable is an array of attributes that are mass-assignable, and guarded is an array of attributes that are not mass-assignable:

protected $fillable = ['attribute1', 'attribute2'];
// OR
protected $guarded = ['attribute_to_guard'];


6. Define Relationships (Optional):

If your model has relationships with other models, you can define them using Eloquent relationships. For example, if your model has a one-to-many relationship with another model, you can define it like this:

public function relatedModel()
{
    return $this->hasMany(RelatedModel::class);
}

Laravel supports various types of relationships like belongsTo, hasMany, hasOne, belongsToMany, etc.

7. Use the Model:

Now that your model is defined, you can use it to interact with your database. You can create, retrieve, update, and delete records using Eloquent methods.

That's it! You've successfully defined a model in Laravel. Remember to run any necessary database migrations after creating or modifying your models.



=== Happy Coding :)