How to insert, update and delete in Laravel - BOOKC -->

How to insert, update and delete in Laravel

Tuesday, May 2, 2017


If you are just learning about laravel, meaning you are beginner of laravel, you probably want to know about how to do insert, update and delete record of a database table in laravel. If you are beginner this short tutorial is for you.

First of all, in laravel you can create a database table using migration and then if you need to fill some data to the table, you can create database seeder. 

Next, after the migration is running and you have a database table, you need to create a model for that database table, normally the model name is same as the table name.

After the model has been created, you can do pretty much anything, like inserting data, updating data, deleting data and also retrieving the data itself (select query).

Inserting data/record in laravel
Let's say i have table named cars and i have model called Car (car.php), to insert data i do this:
$new_car = new Car();
$new_car->model_name = 'NSX';
$new_car->manufature = 'Accura';
$new_car->save();
Let's insert another data:
$new_car = new Car();
$new_car->model_name = 'Impressa WRX';
$new_car->manufature = 'Subaru';
$new_car->save();

Updating data/record in laravel
To update a record first we need to find the record that we want to update using it's unique id (primary key). And then you can update the field and save.
$id = '1';
$update_car = Car::find($id);
$update_car->manufacture = 'Honda';
$update_car->save();
Basically updating record is same as inserting, except first you need to find the specific record using the id of the record, in the above code the id is 1.

Deleting data/record in laravel
To delete a record, just like update you need to find the specific record first and then to delete run the delete() method.
$id = '2';
$update_car = Car::find($id);
$update_car->delete();

Retrieving the data/record in laravel
$cars = Car::get();
foreach ($cars as $car) {
echo($car->manufacture);
}

That's it guys, i hope these example codes can help someone out there who learn about laravel, the best way of learning laravel is by trying it out for your self, the more you code in laravel the better your skill will be.