James H
James H

Reputation: 171

SQL queries from database with Laravel

I'm using Laravel and trying to do an SQL query from my Controller in a public function, but I'm really confused where I would put my table in the argument and if quotes go around the argument. Here is my code

 public function selectMethod(){
    $results = DB::select('select firstname from people where id = 1');
    print_r($results);
    return view('pages.selectMethod');
}

table is called people

My .env is configured to my database correctly and I get this error

FatalErrorException in AboutController.php line 90: Class 'App\Http\Controllers\DB' not found

Thanks !

Upvotes: 0

Views: 111

Answers (2)

Abhishek
Abhishek

Reputation: 3967

Your error clearly states: Class 'App\Http\Controllers\DB' not found

Hence just use DB in your class. Add:

use DB;

At the top of the file just below the namespace line.

Also, I would suggest you to use Eloquent for your queries. It will make your life a lot easier and your code a lot beautiful.

Upvotes: 1

Seifeddine Besbes
Seifeddine Besbes

Reputation: 404

you should add use Illuminate\Support\Facades\DB; at the top of your page for example :

    <?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * Show a list of all of the application's users.
     *
     * @return Response
     */
    public function index()
    {
        $users = DB::table('users')->get();

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

Upvotes: 1

Related Questions