Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class 'App\Http\Controllers\DB' not found in Laravel 5 Controller

I have a problem using the laravel 5 query builder for an Employee management system. Here is my EmployeesController

<?php

namespace App\Http\Controllers;

use App\Employee;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class EmployeesController extends Controller
{

    public function index()
    {
        // $employees = Employee::all();
        // return view('employees.index', compact('employees'));

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

        return view('employees.index', compact('employees'));
    }

}

When i use the commented out code, the view works and i can see my employee list

$employees = Employee::all();
return view('employees.index', compact('employees'));

I saw an answer here, and i did as suggested but no luck. I added use DB; after the namespace declaration and also tried the code with

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

but it throws another error which says Call to a member function count() on a non-object on line 6. I even copied the DB.php file from C:\xampp\htdocs\laravel5project\vendor\laravel\framework\src\Illuminate\Support\Facades to the App folder (C:\xampp\htdocs\laravel5project\app) but still no luck. I've also tried to explicitly give it the namespace

use Illuminate\Support\Facades\DB

Here is the view

@extends('layouts.default')
@section('PageTitle', 'Employee List')
@section('content')

@if ( !$employees->count() )
    There are no Employees!
@else    

<table id="tblEmployee" class="table table-striped table-bordered" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Name</th>
        </tr>
    </thead>

    <tbody>
        @foreach( $employees as $employee )
        <tr>             
            <td>{{$employee->Name}}</td>
        </tr>
        @endforeach

    </tbody>
</table>

@endif
@endsection

What could be the problem?

like image 474
user3659497 Avatar asked Oct 13 '15 15:10

user3659497


1 Answers

DB is not in your current namespace App\Http\Controllers. So you can either import it at the top

use DB;

or precede it with a backslash \DB::table(...). This solves the class not found exception.

You are however not getting a Laravel Collection of Employee models but an array of database rows. Arrays are not objects that have a count() function which results in your final error.

Update: Laravel 5.3 will return a Collection object and not an array. So count() will work on that.

like image 146
mniess Avatar answered Sep 24 '22 12:09

mniess