0
0
Laravelframework~5 mins

Select queries in Laravel

Choose your learning style9 modes available
Introduction

Select queries let you get data from your database so your app can show or use it.

When you want to show a list of users on a page.
When you need to find a product by its ID.
When you want to get all posts written by a specific author.
When you want to filter data by some condition, like all orders above $100.
Syntax
Laravel
DB::table('table_name')->select('column1', 'column2')->get();

You use DB::table('table_name') to start a query on a table.

select() chooses which columns to get. get() runs the query and returns results.

Examples
Gets the name and email of all users.
Laravel
DB::table('users')->select('name', 'email')->get();
Gets id and name of products costing more than 100.
Laravel
DB::table('products')->where('price', '>', 100)->select('id', 'name')->get();
Gets the first order record from the orders table.
Laravel
DB::table('orders')->first();
Sample Program

This code fetches all users from the 'users' table, selecting only their name and email. Then it prints each user's name and email on a new line.

Laravel
<?php
use Illuminate\Support\Facades\DB;

// Get all users with their name and email
$users = DB::table('users')->select('name', 'email')->get();

foreach ($users as $user) {
    echo "Name: {$user->name}, Email: {$user->email}\n";
}
OutputSuccess
Important Notes

Always use select() to get only the columns you need. It makes your app faster.

Use where() to filter results before getting them.

get() returns a collection of results, while first() returns just one record.

Summary

Select queries get data from your database tables.

Use DB::table('table')->select(...)->get() to fetch data.

Filter with where() and choose columns with select().