Laravel Model


What is a model in Laravel?

In Laravel, a model represents a single table in the database and is used to interact with that table's data. Models allow you to perform CRUD (Create, Read, Update, Delete) operations on your database in an object-oriented way without writing raw SQL queries. Each model corresponds to a table, and each instance of the model represents a single row in that table.


How do you create a model in Laravel?

To create a new model, you can use the Artisan command make:model. This will generate a new model class in the app/Models directory.

Example command to create a model:

php artisan make:model Post

This command creates a Post model class in the app/Models directory.


What is the default table name for a model in Laravel?

By default, Laravel assumes the table name for a model is the plural form of the model's class name. For example, if you have a Post model, Laravel will assume the corresponding table is named posts.

If you want to specify a custom table name, you can define the $table property in the model:

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

In this example, the model will interact with the my_custom_table table instead of the default posts table.


How do you define primary keys in a Laravel model?

By default, Laravel assumes that the primary key for a table is an auto-incrementing integer column named id. However, you can customize this behavior by defining the $primaryKey property in the model.

Example of defining a custom primary key:

class Post extends Model
{
    protected $primaryKey = 'post_id';
}

In this example, the model uses the post_id column as the primary key instead of the default id.


How do you disable auto-incrementing for the primary key in a model?

If your primary key is not an auto-incrementing integer, you can disable auto-incrementing by setting the $incrementing property to false.

Example of disabling auto-incrementing:

class Post extends Model
{
    protected $primaryKey = 'uuid';
    public $incrementing = false;
}

In this example, the model uses a UUID as the primary key, and auto-incrementing is disabled.


How do you specify a non-integer key type in a model?

If your primary key is not an integer (e.g., a string or UUID), you can specify the key type by setting the $keyType property in the model.

Example of specifying a non-integer key type:

class Post extends Model
{
    protected $primaryKey = 'uuid';
    public $incrementing = false;
    protected $keyType = 'string';
}

In this example, the primary key is a string (UUID), and Laravel will treat it accordingly.


How do you disable timestamps in a model?

By default, Laravel expects created_at and updated_at timestamp columns to be present in the table. If your table does not use timestamps, you can disable them by setting the $timestamps property to false.

Example of disabling timestamps:

class Post extends Model
{
    public $timestamps = false;
}

In this example, the model will not expect created_at and updated_at columns in the posts table.


How do you define fillable attributes in a model?

The $fillable property in a model allows you to specify which attributes are mass-assignable. This helps prevent mass-assignment vulnerabilities by explicitly allowing certain fields to be filled with user input.

Example of defining fillable attributes:

class Post extends Model
{
    protected $fillable = ['title', 'content', 'user_id'];
}

In this example, only the title, content, and user_id fields can be mass-assigned when creating or updating a Post instance.


How do you define guarded attributes in a model?

The $guarded property is the opposite of $fillable and defines which attributes should not be mass-assignable. If you want to guard all attributes by default, you can set $guarded to an empty array.

Example of defining guarded attributes:

class Post extends Model
{
    protected $guarded = ['admin'];
}

In this example, the admin field cannot be mass-assigned, protecting it from unauthorized updates.


How do you define relationships in a model?

Models in Laravel support relationships such as one-to-one, one-to-many, and many-to-many. Relationships are defined using methods in the model class.

Example of defining a one-to-many relationship:

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

In this example, a User model can have many related Post models.


How do you define an accessor in a Laravel model?

An accessor allows you to format or manipulate a model attribute when retrieving it. Accessors are defined using the getAttributeNameAttribute naming convention in the model.

Example of defining an accessor:

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

In this example, the full_name attribute is dynamically created by combining the first_name and last_name attributes.


How do you define a mutator in a Laravel model?

A mutator allows you to modify the value of a model attribute before saving it to the database. Mutators are defined using the setAttributeNameAttribute naming convention.

Example of defining a mutator:

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

In this example, the password attribute is automatically hashed before being saved to the database.


How do you use soft deletes in a model?

Soft deletes allow you to mark records as deleted without actually removing them from the database. To use soft deletes, you can include the SoftDeletes trait in the model and add a deleted_at column to the table.

Example of enabling soft deletes:

use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes;
    
    protected $dates = ['deleted_at'];
}

In this example, the Post model supports soft deletes, meaning records will be marked as deleted by setting the deleted_at timestamp instead of being removed from the database.


How do you use eager loading with a model?

Eager loading allows you to load related models when querying a model, reducing the number of database queries. You can use the with() method to eager load relationships.

Example of using eager loading:

$users = User::with('posts')->get();

In this example, all users are retrieved along with their related posts in a single query.


How do you cast attributes in a Laravel model?

Attribute casting allows you to convert attributes to a specific data type when retrieving or saving them. You can define the casts in the $casts property of the model.

Example of casting attributes:

class Post extends Model
{
    protected $casts = [
        'is_published' => 'boolean',
        'published_at' => 'datetime',
    ];
}

In this example, the is_published attribute is cast to a boolean, and the published_at attribute is cast to a datetime object.


How do you query scopes in a model?

Query scopes allow you to define common query logic inside a model, making it reusable. You can define query scopes by prefixing a method with scope and calling it directly on the model query.

Example of defining a query scope:

class Post extends Model
{
    public function scopePublished($query)
    {
        return $query->where('is_published', true);
    }
}

Example of using the query scope:

$posts = Post::published()->get();

In this example, the published() scope is used to retrieve only the posts that are marked as published.

Ads