我在员工管理系统中使用laravel 5查询生成器时遇到问题.这是我的员工管理员

<?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'));
    }

}

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

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

我在这里看到了answer,我按照建议做了,但没有运气.我添加了use DB;在名称空间声明之后,还try 了

$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

这里是风景

@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 is not in your current namespace App\Http\Controllers. So you can either import it at the top

use DB;

或者在它前面加一个反斜杠\DB::table(...).这解决了类not found异常.

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.

更新:Laravel 5.3将返回集合对象,而不是array.因此count()将对此进行处理.

Laravel相关问答推荐

Laravel:如何从不断更新的Controller中分页数据

使用MAATWebSite/EXCEL导入Exel时,不会创建Laravel模型

CKEditor在laravel中的p标记之前和之后添加额外的p标记

如何正确使用 Spatie\Laravel Data 来获取数据?

在 Laravel 中设置多个 Vue 组件的问题

未捕获的 TypeError:Vue.component 不是函数

Laravel 5.4 - 如何为同一个自定义验证规则使用多个错误消息

Laravel 中间件返回(try 获取非对象的属性 headers)错误

Laravel Blade 模板 @foreach 订单

将 Laravel MYSQL 更改为 utf8mb4 以在现有数据库中支持表情符号

带有消息...必须返回关系实例的 LogicException.

用 laravel 表单确认删除?

Laravel - 超过 PHP 最大上传大小限制时验证文件大小

laravel 预期响应代码 250 但得到代码530

你如何在自定义 Laravel Nova 工具中使用确认对话?

如何在 Laravel 5.1 中改变环境?

Laravel 5 - 为包创建 Artisan 命令

如何在laravel中获取列值的平均值

Laravel 验证存在于不存在的地方

Laravel - artisan不工作