To fetch data from a database table in Laravel, you can use the DB
class or the Eloquent ORM.
Here’s an example of how you can use the DB
class:
1 2 3 4 5 6 7 |
$users = DB::table('users')->get(); foreach ($users as $user) { echo $user->name; } |
The get
method will return all records in the users
table. You can also use the select
method to specify which columns to select, and the where
method to specify a condition for the query.
1 2 3 4 5 6 |
$users = DB::table('users') ->select('name', 'email') ->where('active', 1) ->get(); |
Here’s an example of how you can use Eloquent ORM:
1 2 3 4 5 6 7 8 9 |
use App\User; $users = User::all(); foreach ($users as $user) { echo $user->name; } |
The all
method will return all records in the users
table. You can also use the where
method to specify a condition for the query, and the get
method to execute the query.
1 2 3 |
$users = User::where('active', 1)->get(); |
You can also use the find
method to fetch a single record by its primary key.
1 2 3 |
$user = User::find(1); |