【发布时间】:2019-12-02 04:44:56
【问题描述】:
我有一个简单的模式,它有一个索引方法来从数据库中获取数据
模态:国家
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Nation extends Model{
function index(){
Nation::where(['visible'=>1])->get();
}
}
现在我想从控制器调用这个函数:
控制器:
$nations = Nation::index();
为了做到这一点,我以这种方式创建了一个外观:
- 创建了一个提供者
- 在 config/app.php 中注册了提供者
- 创建立面
- 在config/app.php中注册了别名
第 1 步 - 提供者:
php artisan make:provider NationServiceProvider
public function register() {
$this->app->bind('nation',function(){
return new Nation();
});
}
第 2 步:在 config/app.php 中注册提供程序
在提供者数组中:
App\Providers\NationServiceProvider::class,
第 3 步创建立面
我在文件 NationFacade.php
中创建了一个文件夹 App/Facades/namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class NationFacade extends Facade{
protected static function getFacadeAccessor(){
return 'nation';
}
}
第四步:在config/app.php中注册别名
在别名数组中:
'Nation' => App\Facades\NationFacade::class
但是,当我运行控制器时,我得到了错误:
"message": "Non-static method App\\Models\\Nation::index() should not be called statically",
我还尝试清除缓存和作曲家转储。我在这里缺少什么?
感谢您的任何建议!
【问题讨论】:
-
在你的国家模型中,公开索引函数。
-
尝试不使用别名调用。即)
NationFacade::index()。 AFAIK,呼叫直接来自Nation模型,这不应该发生。调用应该发生在外观中,它应该解析方法并调用它。 -
@NazmulAbedin,谢谢!我错过了。
-
@CerlinBoss。没有别名,我找不到!所以我意识到缺少“使用”(我认为它是由引导程序制作的)。如果我添加“使用 App\Facades\NationFacade;”有用!但现在我很困惑:我必须使用别名做什么?
标签: laravel eloquent laravel-facade