如何在自定义 Laravel 5.3 配置文件中调用模型?

How do I call a model in a custom Laravel 5.3 config file?

我正在尝试为我的应用程序设置全局变量。

我看到了一些建议,自定义配置文件就是其中之一。

所以我在 config 目录下创建了一个 constraints.php 文件。

这是示例代码:

    return [
       'user_exist'=>1 
    ];

我可以使用 config('constraints.user_exist')

访问这个值

所以我尝试了以下代码:

    return [
       'user_exist'=>count(\App\User::first())
    ];

但它抛出以下错误: PHP 致命错误:在 中调用 null 成员函数 connection() project/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php 第 3308 行

应用程序配置是在 Laravel 引导数据库层之前收集的,因此您此时无权访问基础数据库集合。您最好在应用程序加载后设置此配置变量,也许在 AppServiceProvider.

boot 方法中
config(['constraints.user_exist', count(\App\User::first())])

此外,如果您只是想检查是否有任何用户模型已保存到数据库中,您可能只需要 \App\User::exists()

扩展@Dwight 的答案,我可以通过在 A​​ppServiceProviderboot 方法中设置一个新的配置变量来找到我预期的输出

use Illuminate\Support\Facades\Config;


Config::set('user_exist', User::exists());

并访问此值:

config('user_exist')

第 1 步: 示例:假设您想访问配置文件中的用户模型,然后转到您的配置文件并在 app.php

中添加以下代码
'user_model' => App\Models\User::class,

第二步: 现在您可以在您的应用程序中的任何地方使用此 user_model。只需调用

$user = config('app.user_model'); // app in file name

现在,

  1. 假设您想访问所有用户数据

$user::all();

  1. 假设您想使用用户 ID
  2. 访问特定的用户数据

$user::find(1);