How to perform CRUD (Create, Read, Update, Delete) operations on a model in Laravel?

To perform CRUD operations on a model in Laravel, follow the steps below:

  1. Create a model: Firstly, create a model using the make:model command or manually in the app/Models directory. For example, to create a User model, run php artisan make:model User.

  2. Create a migration: Create a migration for the model using the make:migration command or manually in the database/migrations directory. For example, to create a migration for the User model, run php artisan make:migration create_users_table.

  3. Define the model relationships: In the model file (e.g., User.php), define the relationships with other models using Eloquent relationships like hasMany, belongsTo, etc. For example, if a User model has a hasMany relationship with a Post model, the code would be public function posts() { return $this->hasMany(Post::class); }.

  4. Create data (Create operation): To create a new record in the model's table, use the create method. For example, to create a new user, use $user = User::create(['name' => 'John', 'email' => '[email protected]']);.

  5. Retrieve data (Read operation): To retrieve records from the model's table, use the get method to fetch all or find method to find a specific record by its primary key. For example, to retrieve all users, use $users = User::get(); or to retrieve a specific user with ID 1, use $user = User::find(1);.

  6. Update data (Update operation): To update a record, retrieve the record using find or any other query and then use the update method to modify the desired attributes. For example, to update the name of a user with an ID 1, use User::find(1)->update(['name' => 'Updated Name']);.

  7. Delete data (Delete operation): To delete a record, retrieve the record using find or any other query and call the delete method. For example, to delete a user with an ID 1, use User::find(1)->delete();.

These are the basic steps to perform CRUD operations on a model in Laravel. It is recommended to read the Laravel documentation for more details and advanced operations.