首页 > 解决方案 > 如何在 laravel 5.4 中只在自己的城市看到专家

问题描述

我的项目有两个角色

数据库

管理员必须查看所有城市的所有数据。专家注册后必须查看自己城市的所有数据。

public function index()
{
    $schools = SchoolsList::latest()->paginate(25);
    $city_id = SchoolsList::where('city_id')->first();
    $expert = Role::where('id', '=', 2);
    if ($expert){
        return view('Admin.inspection-failed.all', compact('schools')->where(($city_id)));
    }
    else{
        return view('Admin.inspection-failed.all', compact('schools'));
    }
}

学校表

Schema::create('schools', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users');
    $table->integer('city_id')->unsigned();
    $table->foreign('city_id')->references('id')->on('cities');
    $table->string('school_name');
    $table->string('status');
    $table->string('gender');
    $table->string('notes');
    $table->string('member_name');
    $table->string('type');
    $table->string('file_number');
    $table->string('phone');
    $table->string('address');
});

我想当高手登录。专家显示数据只有自己的专家城市。

我得到这个错误。

调用数组上的成员函数 where()

标签: laravel-5.4

解决方案


此代码中出现错误compact('schools')->where(($city_id));因为compact('schools')它是等价的['schools' => $schools]
请参阅文档 http://php.net/manual/en/function.compact.php
在您的情况下,您的代码是等效的['schools' => $schools]->where(($city_id))。要修复它,您必须使用
Short Answer

$schools = $schools->where('city_id' => $city_id->id);
return view('Admin.inspection-failed.all', compact('schools'));

长答案

$city = City::first(); // you must be fix it yourself
$expert = Role::where('id', '=', 2); // you must be change it

if ($expert) {
    $schools = SchoolsList::latest()->paginate(25);
} else {
    $schools = SchoolsList::where('city_id', $city->id)->latest()->paginate(25);
}

return view('Admin.inspection-failed.all', compact('schools'));

推荐阅读