user860511
user860511

Reputation:

Laravel 5 - Call to undefined method

I am trying to call a method within the model, in my view, but I am being presented with this error:

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

Model: (Site)

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

Controller: (HomeController.php)

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

View: 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

I am unsure why it cannot find this method within the Site model. Many thanks for your help.

Upvotes: 1

Views: 3706

Answers (3)

Captain Hypertext
Captain Hypertext

Reputation: 2506

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

Should be

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

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

If you don't call get(), it'll still be a query builder object. If you call hasLogo() or logo() on $sites, it will fail because that's an eloquent collection, not a model.

Upvotes: 0

Jilson Thomas
Jilson Thomas

Reputation: 7303

Complete your query here:

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

Call get() or first() depending on your need.

and now you'll be able to call your custom method.

Upvotes: 0

Thomas Kim
Thomas Kim

Reputation: 15911

You are not retrieving anything. This is what you have right now:

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

That merely preps the query. You haven't fetched anything until you call a method like first(), get(), etc. So, try this instead:

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

firstOrFail() will also fetch only one site. If you want to fetch all sites that meet the requirement, you will need to use get() and then loop through the sites.

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

Upvotes: 4

Related Questions