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.
1DB_CONNECTION=mysql2DB_HOST=127.0.0.13DB_PORT=33064DB_DATABASE=laravel_db5DB_USERNAME=root6DB_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.
1php 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.
1php 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:
1public function up()2{3Schema::create('users', function (Blueprint $table) {4$table->id(); // Creates an auto-incrementing ID column5$table->string('name');6$table->string('email')->unique(); // Email must be unique7$table->string('password');8$table->timestamps(); // Adds created_at and updated_at columns9});10}
To apply the migration and create the table in your database, run:
1php 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:
1use AppModelsUser;23Route::get('/create-user', function () {4User::create([5'name' => 'Jane Doe',6'email' => 'jane@example.com',7'password' => bcrypt('password123'), // Always encrypt passwords!8]);910return '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:
1Route::get('/users', function () {2$users = User::all(); // Retrieve all users from the database3return view('users.index', compact('users')); // Pass the users to a view4});
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@endforeach14</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
1Route::get('/user/update/{id}', function ($id) {2$user = User::find($id); // Find the user by their ID3$user->name = 'Updated Name'; // Update the user's name4$user->save(); // Save the changes56return '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
1Route::get('/user/delete/{id}', function ($id) {2$user = User::find($id); // Find the user by their ID3$user->delete(); // Delete the user45return '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