Trusted answers to developer questions

How can we use the table() method in Laravel?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

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.

Syntax

$users = DB::table('users')->get();

Explanation

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.

Parameter

The table() receives one parameter:

  1. Name of the table

At the end of the query, the get() method is then chained to fetch the data.

Example

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;
    }
}

Explanation

  • 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;

RELATED TAGS

laravel

CONTRIBUTOR

Chinweuba Elijah Azubuike
Did you find this helpful?