Laravel provides two main approaches for interacting with databases: the query builder and the ORM (Object-Relational Mapping) called Eloquent. The configuration for Laravel's database services is located in the application's config/database.php
configuration file.
• Query Builder :
Laravel Query Builder is a fluent interface for building and running database queries in Laravel without having to write raw SQL statements.
$users = DB::table('users')->select('name', 'email')->get();
$users = DB::table('users')->where('age', '>', 18)->get();
DB::table('users')->insert([
'name' => 'John Doe',
'email' => 'john@example.com',
]);
• Eloquent ORM :
Laravel's Eloquent ORM is an ActiveRecord implementation for working with databases in PHP. It allows you to interact with your database tables using PHP objects. Each database table has a corresponding "model" that is used to interact with that table.
User's Model -
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use HasFactory;
protected $table = "users";
protected $primaryKey = "id";
protected $fillable = [
'name',
'email',
'status',
];
}
User's Controller -
$users = User::where('id', $id)->get()->toArray();
$result = User::create([
'name' => $name,
'email' => $email,
'status' => 1,
]);
$user = User::find($id);
$user->delete();