How To Fetch Data From Database With Example Using Laravel

admin_img Posted By Bajarangi soft , Posted On 01-09-2020

Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works on all supported database systems. The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.

How to Fetch Data From DataBase in Laravel

To get data from table we use SQL SELECT  statement

SELECT * FROM table_name

To learn more about SQL, please visit our BajarangiSoft site.

How to get data in laravel
Let's see


Getting All Rows data From A Table

You may use the table method on the DB facade to begin a query. The table method returns a fluent query builder instance for the given table, allowing you to chain more constraints onto the query and then finally get the results using the get method:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;//include this

class UserController extends Controller
{
    public function index()
    {
        $users = DB::table('users')->get();//query return data in DB method

        return view('user.index', ['users' => $users]);
    }
}
?>

The get method returns an Illuminate\Support\Collection containing the results where each result is an instance of the PHP stdClass object.


Retrieving  Single Row or Column From Table

$user = DB::table('users')->where('name', 'kiran')->first();

echo $user->name;

 Extract a single value from a record using the value method.

$email = DB::table('users')->where('name', 'kiran')->value('email');

Retrieve a single row by its id column value, use the find method:

$user = DB::table('users')->find(7);


Retrieving A List Of Column Values: to retrieve a Collection containing the values of a single column,we can use the pluck method

$name = DB::table('roles')->pluck('name');

foreach ($name as $name ) {
echo $name;
}

Related Post