0
0
Laravelframework~5 mins

Why database integration is core in Laravel

Choose your learning style9 modes available
Introduction

Database integration helps your Laravel app save and get data easily. It connects your app to a place where information lives.

You want to store user details like names and emails.
You need to save posts or comments on a blog.
You want to keep track of orders in an online store.
You need to update information when users change their profile.
You want to show data from the database on your website.
Syntax
Laravel
<?php
use Illuminate\Database\Eloquent\Model;

class User extends Model {
    // Model connects to 'users' table by default
}

// To get all users
$users = User::all();

// To save a new user
$user = new User();
$user->name = 'Alice';
$user->email = 'alice@example.com';
$user->save();

Laravel uses Eloquent ORM to connect models to database tables.

Models let you work with data as simple PHP objects.

Examples
This fetches all products from the database.
Laravel
<?php
// Get all records from 'products' table
$products = Product::all();
This adds a new product to the database.
Laravel
<?php
// Create and save a new product
$product = new Product();
$product->name = 'Book';
$product->price = 9.99;
$product->save();
This updates the email of the user with id 1.
Laravel
<?php
// Find a user by id and update email
$user = User::find(1);
$user->email = 'newemail@example.com';
$user->save();
Sample Program

This example shows how to save a new task and then list all tasks with their status.

Laravel
<?php
use Illuminate\Database\Eloquent\Model;

class Task extends Model {
    // Connects to 'tasks' table
}

// Create a new task
$task = new Task();
$task->title = 'Learn Laravel';
$task->completed = false;
$task->save();

// Get all tasks
$tasks = Task::all();

foreach ($tasks as $task) {
    echo "Task: {$task->title}, Completed: " . ($task->completed ? 'Yes' : 'No') . "\n";
}
OutputSuccess
Important Notes

Always set up your database connection in Laravel's .env file before using models.

Use migrations to create and update database tables safely.

Eloquent makes database work feel like using regular PHP objects.

Summary

Database integration lets Laravel apps save and get data easily.

Eloquent models connect your PHP code to database tables.

This helps build dynamic apps that remember user info and content.