laravel - 在 Laravel 5 Controller 中找不到类 'App\Http\Controllers\DB'

标签 laravel laravel-5

我在使用员工管理系统的 laravel 5 查询生成器时遇到问题。这是我的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'));
    }

}

当我使用注释掉的代码时, View 可以工作,我可以看到我的员工列表

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

我看到了一个answer在这里,我按照建议做了,但没有运气。我添加了使用数据库;在命名空间声明之后,还尝试了

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

但它抛出了另一个错误,即第 6 行的 Call to a member function count() on a non-object(在非对象上调用成员函数 count())。 我什至将 DB.php 文件从 C:\xampp\htdocs\laravel5project\vendor\laravel\framework\src\Illuminate\Support\Facades 复制到 App 文件夹(C:\xampp\htdocs\laravel5project\app),但仍然没有运气。 我还尝试显式为其指定 namespace

use Illuminate\Support\Facades\DB

这是 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

可能是什么问题?

最佳答案

DB 不在您当前的命名空间 App\Http\Controllers 中。所以你可以在顶部导入它

use DB;

或在其前面加上反斜杠\DB::table(...)。这解决了类未找到异常。

但是,您获得的不是 Employee 模型的 Laravel 集合,而是数据库行的数组。数组不是具有 count() 函数的对象,这会导致最终错误。

更新:Laravel 5.3 将返回 Collection 对象而不是数组。所以 count() 可以解决这个问题。

关于laravel - 在 Laravel 5 Controller 中找不到类 'App\Http\Controllers\DB',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33106904/

相关文章:

php - Laravel 5.5, session 依赖路由

postgresql - 如何在不使用 Eloquent 执行查询的情况下显示查询

php - Laravel 持续集成策略

mysql - 架构 getColumnType 不起作用

laravel - 使用 Passport Password Grants 和/或 Guzzle 时服务器卡住

php - Laravel 更新查询

php - Laravel FileSystem中的模糊错误消息

php - Laravel LeftJoin where

php - 如何在 Laravel 中更改我的应用程序的命名空间?

php - 如何在 Laravel 中制作简单的动态下拉列表?