What is Eloquent ORM? Eloquent is Laravel's built-in ORM that allows you to interact with your database using PHP models instead of raw SQL queries. It provides an easy-to-use, object-oriented syntax to manage database records.
Creating a Model: You can create an Eloquent model using the Artisan command make:model
. This will generate a model file that represents a table in your database.
Example:
php artisan make:model Post
This will create a Post
model in the app/Models
directory.
Defining the Table and Columns: By default, Laravel assumes the table name is the plural form of the model name. For example, the Post
model is associated with the posts
table. You can also specify the table name and columns if needed.
Example:
class Post extends Model
{
protected $table = 'blog_posts'; // Custom table name
}
Inserting Data (Creating Records): To insert a new record, you can use the create()
or save()
method.
Example:
$post = new Post;
$post->title = 'New Post Title';
$post->content = 'This is the content of the post.';
$post->save();
Alternatively, you can use the create()
method if you're passing data as an array:
Example:
Post::create([
'title' => 'New Post Title',
'content' => 'This is the content of the post.',
]);
Reading Data (Retrieving Records): Eloquent provides various methods to retrieve data from the database, including all()
, find()
, where()
, and get()
.
Example:
$posts = Post::all();
Retrieve a single record by its primary key:
$post = Post::find(1); // Find post with ID 1
Use query conditions:
$posts = Post::where('title', 'like', '%Laravel%')->get();
Updating Data (Modifying Records): To update an existing record, you can retrieve the model, change its attributes, and save it.
Example:
$post = Post::find(1); // Find post with ID 1
$post->title = 'Updated Post Title';
$post->save();
Deleting Data (Removing Records): To delete a record, you can use the delete()
method.
Example:
$post = Post::find(1); // Find post with ID 1
$post->delete();
Mass Assignment Protection: To protect against mass assignment vulnerabilities, specify which fields can be mass-assigned in the model using the $fillable
or $guarded
property.
Example:
class Post extends Model
{
protected $fillable = ['title', 'content']; // Allow these attributes to be mass-assigned
}
Working with Relationships: Eloquent makes it easy to work with relationships like one-to-many, many-to-many, and one-to-one. For example, if a Post
has many Comments
, you can define a comments()
method in the Post
model.
Example (One-to-Many Relationship):
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
}
Eloquent ORM simplifies working with database records in Laravel by using models and an elegant syntax. By following these steps, you can easily perform CRUD operations, handle relationships, and interact with your database in an object-oriented way. This makes Eloquent a powerful tool for managing data in Laravel applications.