Icon
Get In Touch
#laravel

Database and Eloquent ORM in Laravel

Almost every modern web application interacts with a database. Laravel makes interacting with databases extremely easy across a variety of supported databases using raw SQL, a fluent query builder, and the Eloquent ORM.

Database Configuration

Before we work with any data, we need to tell Laravel how to connect to your database. You will find these settings in the .env file at the root of your project.

1
DB_CONNECTION=mysql
2
DB_HOST=127.0.0.1
3
DB_PORT=3306
4
DB_DATABASE=laravel_db
5
DB_USERNAME=root
6
DB_PASSWORD=password

Creating a Model and a Table

In Laravel, you use models to work with tables in your database. Lets create a simple User model that will represent users in our database. This will create a User.php file inside the app/Models/ folder.

1
php artisan make:model User

Creating a Table with a Migration

Now we need a table in the database to store our users. Laravel uses migrations to help you create and manage database tables. Think of migrations as version control for your database.

1
php artisan make:migration create_users_table

This will generate a migration file in the database/migrations directory. Open the file, and you'll see something like this:

1
public function up()
2
{
3
Schema::create('users', function (Blueprint $table) {
4
$table->id(); // Creates an auto-incrementing ID column
5
$table->string('name');
6
$table->string('email')->unique(); // Email must be unique
7
$table->string('password');
8
$table->timestamps(); // Adds created_at and updated_at columns
9
});
10
}

To apply the migration and create the table in your database, run:

1
php artisan migrate

Inserting Data into Your Table

Now that we have a table, lets add some users to it. You can insert data directly using Eloquent models. Open routes/web.php and add this route to insert a user into your database:

1
use AppModelsUser;
2
3
Route::get('/create-user', function () {
4
User::create([
5
'name' => 'Jane Doe',
6
'email' => 'jane@example.com',
7
'password' => bcrypt('password123'), // Always encrypt passwords!
8
]);
9
10
return 'User created successfully!';
11
});

Visit http://localhost:8000/create-user in your browser, and this route will insert a new user into the database!

Retrieving Data from Your Table

In routes/web.php, add this route:

1
Route::get('/users', function () {
2
$users = User::all(); // Retrieve all users from the database
3
return view('users.index', compact('users')); // Pass the users to a view
4
});

Create a view file at resources/views/users/index.blade.php

When you visit http://localhost:8000/users, you will see a list of users from your database displayed on the page.

1
<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
<meta charset="UTF-8">
5
<meta name="viewport" content="width=device-width, initial-scale=1.0">
6
<title>Users List</title>
7
</head>
8
<body>
9
<h1>List of Users</h1>
10
<ul>
11
@foreach ($users as $user)
12
<li>{{ $user->name }} - {{ $user->email }}</li>
13
@endforeach
14
</ul>
15
</body>
16
</html>

Updating Data in Your Table

Lets say you want to update a users information. Heres how you can do that using a route

Add this route to routes/web.php

1
Route::get('/user/update/{id}', function ($id) {
2
$user = User::find($id); // Find the user by their ID
3
$user->name = 'Updated Name'; // Update the user's name
4
$user->save(); // Save the changes
5
6
return 'User updated successfully!';
7
});

When you visit http://localhost:8000/user/update/1, the user with ID 1 will have their name updated to "Updated Name.

Deleting Data from Your Table

Add this route to routes/web.php

1
Route::get('/user/delete/{id}', function ($id) {
2
$user = User::find($id); // Find the user by their ID
3
$user->delete(); // Delete the user
4
5
return 'User deleted successfully!';
6
});

When you visit http://localhost:8000/user/delete/1, the user with ID 1 will be deleted from the database.

These are the core database operations you will use in almost every Laravel app. With this knowledge, you can start building real-world applications like user management systems, blog platforms, or any app that requires data storage.

©2024 Codeblockz

Privacy Policy