CLOSE

Understanding Models

In the MVC (Model-View-Controller) architecture, models represent the data and business logic of an application. In Laravel, models are PHP classes that map to database tables, allowing you to query and manipulate data using object-oriented techniques.

An Eloquent model represents a database table and provides a convenient way to interact with that table.

  • Each Eloquent models corresponds to a single table in the database.

Creating Models

Creating a model in Laravel is simple. Use the php artisan make:model command followed by the model name.

php artisan make:model User

This command generates a User.php file in the app/Models directory by default, representing the users database table.

Defining Attributes and Relationships

Models define the structure of your data, including attributes (columns) and relationships (associations between tables). Let's explore how to define attributes and relationships in Laravel models.

Attributes:

Attributes represent the columns of a database table. They are defined as properties in the model class.

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $fillable = ['name', 'email']; // Define fillable attributes

    protected $guarded = ['id']; // Define guarded attributes
}

Defining a Table:

By default, Eloquent assumes that the table associated with a model is named after the model in a plural, snake_case format. If your table name is different, to that of model, you can specify it in the model:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $table = 'blog_posts';
}

Relationships:

Relationships define how models are associated with each other. Laravel supports various types of relationships, including one-to-one, one-to-many, and many-to-many.

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

Accessors and Mutators:

Accessors and mutators allow you to manipulate attribute values before retrieving or saving them to the database.

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function getFullNameAttribute()
    {
        return $this->first_name . ' ' . $this->last_name;
    }

    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);
    }
}