Laravel Eloquent ORM
What is Eloquent ORM in Laravel?
Eloquent ORM is Laravel's built-in Object-Relational Mapping (ORM) system. It provides an easy and expressive way to interact with databases by representing database tables as models. Eloquent allows developers to perform CRUD operations and build complex queries without needing to write raw SQL. Each Eloquent model corresponds to a table in the database, and each instance of the model represents a single row in that table.
How do you define a model in Eloquent?
You can define an Eloquent model by creating a class that extends the Illuminate\Database\Eloquent\Model class. The model class corresponds to a database table, and each instance of the class represents a row in that table.
Example of defining a model:
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
// The table associated with the model
protected $table = 'users';
}
In this example, the User model corresponds to the users table in the database.
How do you retrieve all records from a table using Eloquent?
You can retrieve all records from a table using the all() method provided by Eloquent. This method returns a collection of all rows in the table.
Example of retrieving all records:
$users = User::all();
In this example, all rows from the users table are retrieved and stored in the $users variable.
How do you find a record by its primary key using Eloquent?
You can find a record by its primary key using the find() method. This method retrieves a record by its ID and returns an instance of the model.
Example of finding a record by its primary key:
$user = User::find(1);
In this example, the user with an ID of 1 is retrieved from the users table.
How do you use the where clause in Eloquent?
You can filter records using the where() method in Eloquent. The where() method applies a condition to the query and returns a collection of records that match the condition.
Example of using the where clause:
$users = User::where('age', '>', 18)->get();
In this example, all users older than 18 are retrieved from the users table.
How do you insert data using Eloquent?
You can insert data into the database by creating an instance of an Eloquent model, setting the attributes, and calling the save() method.
Example of inserting data:
$user = new User;
$user->name = 'John Doe';
$user->email = '[email protected]';
$user->password = bcrypt('password');
$user->save();
In this example, a new user is created and inserted into the users table.
How do you update records using Eloquent?
To update an existing record, you can find the record using Eloquent's find() or where() method, modify the attributes, and then call save() to persist the changes.
Example of updating data:
$user = User::find(1);
$user->name = 'John Updated';
$user->save();
In this example, the user with an ID of 1 is retrieved, their name is updated, and the changes are saved to the database.
How do you delete records using Eloquent?
To delete a record, you can use the delete() method after finding the record using find() or where().
Example of deleting a record:
$user = User::find(1);
$user->delete();
In this example, the user with an ID of 1 is deleted from the users table.
What is the fillable property in Eloquent?
The fillable property in Eloquent defines which attributes can be mass-assigned. This is a security feature that prevents mass-assignment vulnerabilities by specifying which fields are allowed to be filled with user input.
Example of using the fillable property:
class User extends Model
{
protected $fillable = ['name', 'email', 'password'];
}
In this example, only the name, email, and password fields are allowed to be mass-assigned.
How do you define relationships in Eloquent?
Eloquent supports defining relationships between models, such as one-to-many, many-to-many, and one-to-one. You can define relationships using methods in the model classes.
Example of defining a one-to-many relationship:
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
In this example, the posts() method defines a one-to-many relationship between the User and Post models, indicating that a user can have many posts.
How do you use eager loading in Eloquent?
Eager loading allows you to load related models alongside the main model, reducing the number of queries executed. You can use the with() method to perform eager loading.
Example of using eager loading:
$users = User::with('posts')->get();
In this example, all users are retrieved along with their related posts, reducing the number of queries to the database.
How do you use the belongsTo relationship in Eloquent?
The belongsTo relationship is used to define a relationship where a model belongs to another model. For example, a post belongs to a user.
Example of using the belongsTo relationship:
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
In this example, the user() method defines a relationship where a post belongs to a user.
How do you use the hasMany relationship in Eloquent?
The hasMany relationship is used to define a relationship where a model can have many related models. For example, a user can have many posts.
Example of using the hasMany relationship:
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
In this example, the posts() method defines a relationship where a user can have many posts.
How do you use the many-to-many relationship in Eloquent?
The belongsToMany relationship defines a many-to-many relationship between models. For example, a user can belong to many roles, and a role can belong to many users.
Example of using a many-to-many relationship:
class User extends Model
{
public function roles()
{
return $this->belongsToMany(Role::class);
}
}
In this example, the roles() method defines a many-to-many relationship between users and roles.
How do you use one-to-one relationships in Eloquent?
The hasOne relationship defines a one-to-one relationship between models. For example, a user can have one profile.
Example of using a one-to-one relationship:
class User extends Model
{
public function profile()
{
return $this->hasOne(Profile::class);
}
}
In this example, the profile() method defines a one-to-one relationship where a user has one profile.
How do you use the withTrashed method in Eloquent?
The withTrashed method allows you to retrieve soft deleted records from the database. Soft deleting means that a record is not actually removed from the database but is marked as deleted using a deleted_at timestamp.
Example of retrieving soft deleted records:
$users = User::withTrashed()->get();
In this example, all users, including those that have been soft deleted, are retrieved from the database.
How do you use the onlyTrashed method in Eloquent?
The onlyTrashed method retrieves only the soft deleted records from the database.
Example of retrieving only soft deleted records:
$users = User::onlyTrashed()->get();
In this example, only the users who have been soft deleted are retrieved from the database.
How do you use the restore method in Eloquent?
The restore method is used to restore soft deleted records. It sets the deleted_at field to null, effectively restoring the record.
Example of restoring a soft deleted record:
$user = User::withTrashed()->find(1);
$user->restore();
In this example, the soft deleted user with an ID of 1 is restored.
How do you use the forceDelete method in Eloquent?
The forceDelete method permanently deletes a record from the database, bypassing soft deletion.
Example of force deleting a record:
$user = User::withTrashed()->find(1);
$user->forceDelete();
In this example, the user with an ID of 1 is permanently deleted from the database.