Laravel : How to Establish Database Connection and Perform CRUD Operations

İbrahim Halil Oğlakcı
3 min readAug 10, 2023

--

Laravel is a popular PHP framework that simplifies the process of building web applications. One of the fundamental aspects of web development is database management, including connecting to databases and performing CRUD (Create, Read, Update, Delete) operations. In this article, we’ll cover how to establish a database connection and perform basic CRUD operations using Laravel.

1. Establishing Database Connection:

To establish a database connection in Laravel, follow these steps:

Step 1: Open the .env file in the root directory of your Laravel project.

Step 2: Locate the database configuration section and fill in the necessary details like DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME, and DB_PASSWORD.

Step 3: Laravel uses the Eloquent ORM by default, which handles database connections. You can access the database connection using the DB facade.

Example code:

$users = DB::table('users')->get();

2. Creating Records (Create Operation):

To insert records into a database table, follow these steps:

Step 1: Import the required classes at the top of your controller or model:

use Illuminate\Support\Facades\DB;

Step 2: Use the insert method to add records to the table:

Example code:

DB::table('users')->insert([
'name' => 'John Doe',
'email' => 'johndoe@example.com',
'created_at' => now(),
'updated_at' => now(),
]);

3. Reading Records (Read Operation):

To retrieve records from a database table, follow these steps:

Step 1: Use the select method to fetch records from the table:

Example code:

$users = DB::table(‘users’)->select(‘name’, ‘email’)->get();

Step 2: Loop through the retrieved records to display or manipulate them.

Example code:

foreach ($users as $user) {
echo $user->name . ' - ' . $user->email;
}

4. Updating Records (Update Operation):

To update records in a database table, follow these steps:

Step 1: Use the update method along with the where clause to specify which records to update:

Example code:

DB::table('users')
->where('id', 1)
->update(['name' => 'Updated Name']);

5. Deleting Records (Delete Operation):

To delete records from a database table, follow these steps:

Step 1: Use the delete method along with the where clause to specify which records to delete:

Example code:

DB::table('users')
->where('id', 1)
->delete();

This article covers the basics of establishing a database connection and performing CRUD operations in Laravel. By following these steps and examples, you’ll be well on your way to building efficient and powerful web applications using Laravel’s database capabilities.

Happy Coding…

--

--