How to select / get values from database in laravel?

by lindsey.homenick , in category: PHP Frameworks , 6 months ago

How to select / get values from database in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jerad , 6 months ago

@lindsey.homenick 

To select/get values from a database in Laravel, you can use Eloquent ORM, query builder, or raw SQL queries. Below are examples of how you can retrieve data from a database using each of these methods:

  1. Using Eloquent ORM:
1
2
3
4
5
6
7
8
// Retrieve all records from a table
$users = User::all();

// Retrieve a single record by its primary key
$user = User::find(1);

// Retrieve records based on a condition
$users = User::where('name', 'John')->get();


  1. Using Query Builder:
1
2
3
4
5
6
7
8
// Retrieve all records from a table
$users = DB::table('users')->get();

// Retrieve a single record by its primary key
$user = DB::table('users')->where('id', 1)->first();

// Retrieve records based on a condition
$users = DB::table('users')->where('name', 'John')->get();


  1. Using Raw SQL Queries:
1
2
3
4
5
6
7
8
// Retrieve all records from a table
$users = DB::select('SELECT * FROM users');

// Retrieve a single record by its primary key
$user = DB::select('SELECT * FROM users WHERE id = ?', [1]);

// Retrieve records based on a condition
$users = DB::select('SELECT * FROM users WHERE name = ?', ['John']);


It is recommended to use Eloquent ORM or Query Builder in Laravel for retrieving data from the database as they provide a more expressive syntax and are more secure against SQL injection attacks.