Basic CRUD Operation In Laravel

A simple tutorial how to create a connection database and implement simple CRUD operation ,CRUD is four basic function of persistent storage. Some people defining function of CRUD as retrieve instead of read, modify instead of update, or destroy instead of delete. In this article i want to share how to implement that four basic function.

Starting from creating connection, to creating a connection you need to edit .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE={Your database name}
DB_USERNAME={Your localhost username}
DB_PASSWORD={Your localhost password}

You only need to edit code in curly braces, adjust it to your localhost configuration. note: don’t include the curly braces


Running Select queries

If you want to Get multiple data you can use method get(), it will return data in array.

$data[‘datas’]= DB::table(‘table_name’)->get();return view('viewName',$data);

You can pass your data to your view by returning view along with $data, and at your view you need to call $datas variable instead of $data.

To retrieve single data from database you can use method first() to retrieve the record of the table, if you want to retrieve specific record you can use where() clause constraint before first().

$data[‘datas’]= DB::table(‘table_name’)->where('id',1)->first();

Running Insert Queries

To insert a data you can use insert() clause.

$data = array(‘name’ => 'Toby',
’email’ => 'toby@example.com'
);
$query = DB::table(‘pesan’)->insert($data);

Or you can use insert() as a method.

DB::insert('insert into users (id, name) values (?, ?)', [1, 'toby']);

Running Delete Queries

To delete or destroy the entire records in table you can use delete() method and the number of affected rows will be returned.

$delete = DB::delete('delete from table');

If you want to delete specific record you only need to put where() clause before delete().

$delete= DB::table(‘pesan’)->where(‘id’, 3)->delete();

Running Update Queries

To execute update of existing record you can use update() method, the input should be an array.

$datas = DB::update('update users set votes = 100 where name = ?', ['toby']);

Or like the other you can use the other method to update you data.

$data = array('name' => $names );
$datas = DB::table(‘pesan’)->where(‘name’,$name)->update($data);

And just like delete the number of affected rows will be returned to $datas.


That all for this article, i hope this can help you.

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade