Laravel 5 - 调用未定义的方法

Laravel 5 - Call to undefined method

在我看来,我正在尝试调用模型中的方法,但出现了以下错误:

Call to undefined method Illuminate\Database\Query\Builder::hasLogo() (View: /Users/Documents/audit/resources/views/misc/logo.blade.php)

型号:(网站)

  public function hasLogo()
  {
    return File::exists(public_path($this->logo->url()));
  }

控制器:(HomeController.php)

  public function showLogo()
  {
    $sites = Site::where('user_id', Auth::id());
    return View::make('misc.logo')->with(['sites' => $sites]);
  }

查看:logo.blade.php

@if ($sites->hasLogo())

<img src="<?= $sites->logo->url('medium') ?>" alt="<?= $sites->name ?>" 
          class="img-rounded col-md-12" style="padding-bottom: 20px;">

@endif

我不确定为什么在 Site 模型中找不到此方法。非常感谢您的帮助。

您没有检索任何内容。这是你现在拥有的:

$sites = Site::where('user_id', Auth::id());

这只是准备查询。在调用 first()get() 等方法之前,您还没有获取任何东西。因此,试试这个:

$sites = Site::where('user_id', Auth::id())->firstOrFail();

firstOrFail() 也只会获取一个站点。如果您想获取所有符合要求的网站,您将需要使用 get() 然后循环访问这些网站。

$sites = Site::where('user_id', Auth::id())->get();
foreach ($sites as $site)
{
    if ($site->hasLogo())
    {
        // etc.
    }
}

在这里完成您的查询:

$sites = Site::where('user_id', Auth::id())->get();

根据需要致电get()first()

现在您可以调用您的自定义方法了。

$sites = Site::where('user_id', Auth::id());

应该是

$sites = Site::where('user_id', Auth::id())->get(); // ->get() the data

foreach($sites as $site) {
    if( $site->hasLogo() ) {
        // do stuff
    }
}

如果您不调用 get(),它仍然是一个查询生成器对象。如果您在 $sites 上调用 hasLogo()logo(),它将失败,因为那是 eloquent collection,而不是模型。