The table()
method is used to retrieve data from a particular table in a database and allows for the chaining of Laravel query builders in order to get the desired result.
$users = DB::table('users')->get();
From the syntax, you will notice that the table()
method is called on the DB
facade.
Note: Ensure to import this class
use Illuminate\Support\Facades\DB;
The DB
facade gives an instance of the database your application is connected to, allowing it to select from whatever table that is passed as the parameter.
The table()
receives one parameter:
At the end of the query, the get()
method is then chained to fetch the data.
You will need to paste the index()
function in any controller to practice this:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
class UserController extends Controller
{
public function index()
{
$users = DB::table('users')->get();// fetching data from the users table
return $users;
}
}
We pass the users
to the table()
method.
The table()
selects the users
table from the database.
Also be sure to import:
use Illuminate\Support\Facades\DB;