Eloquent is the Object-Relational Mapping (ORM) system included with the Laravel PHP framework. It provides an elegant and expressive way to interact with your database by allowing you to work with database tables using object-oriented syntax. Below are some common operations and examples of how to use Eloquent for database queries in Laravel.
Create a model using Artisan command:
php artisan make:model YourModel |
// Create a new instance of the model $record = new YourModel; // Set the attributes $record->column1 = 'value1'; $record->column2 = 'value2'; // Save the record to the database $record->save(); |
$records = YourModel::all(); |
$record = YourModel::find($id); |
$records = YourModel::where('column', 'value')->get(); |
// Find the record by ID $record = YourModel::find($id); // Update the attributes $record->column1 = 'new_value1'; $record->column2 = 'new_value2'; // Save the changes to the database $record->save(); |
// Find the record by ID $record = YourModel::find($id); // Delete the record $record->delete(); |
// Create a new record $record = YourModel::create([ 'column1' => 'value1', 'column2' => 'value2', ]); // Update a record YourModel::where('id', $id)->update([ 'column1' => 'new_value1', 'column2' => 'new_value2', ]); |
// Post Model class Post extends Model { public function comments() { return $this->hasMany(Comment::class); } } // Comment Model class Comment extends Model { // ... } // Access comments for a post $post = Post::find($postId); $comments = $post->comments; |
These are just some basic examples, and Eloquent provides many other features for complex queries, eager loading, and more. Refer to the Laravel documentation for a comprehensive guide: Eloquent ORM - Laravel Documentation.
=== Happy Coding :)