skip to Main Content

I have this fetch function, it fetches the full feed if no user is selected, and it fetches a specific user’s feed if it is.

public function fetch(): void
{
    if ($this->userToShowFeedFor == null) {
       $this->tweets = Tweet::with('user')->withCount('likes')->get();
    } else {
       $this->tweets = $this->userToShowFeedFor->tweets;
    }
}

in my blade template I have this:

@if (!$userToShowFeedFor)
      <a wire:navigate href="{{ route('userpage', ['user' => $tweet->user]) }}"
         class="text-gray-600 cursor-pointer underline">u/{{ $tweet->user->username }}</a>
@else
    <p class="inline text-gray-600 ">u/{{ $tweet->user->username }}</p>
@endif

Despite using the with('user') I am still getting this error.

enter image description here

I even used tinker to make sure I wasn’t doing any bad SQL queries under the hood and it looks all good.

enter image description here

2

Answers


  1. Check in your app the istruction Model::preventLazyLoading, tipically is set in the boot method of the AppServiceProvider class.
    If it is set, when you try to lazy load a model, an exception is throwed.

    Here the documentation

    Login or Signup to reply.
  2. i think the runtime code is different than u expected i think it hits the else case on that exception to can you try to add load('user') to at the end to be like that

    public function fetch(): void
    {
        if ($this->userToShowFeedFor == null) {
           $this->tweets = Tweet::with('user')->withCount('likes')->get();
        } else {
           $this->tweets = $this->userToShowFeedFor->tweets->load('user');
        }
    }
    

    load works the same as with but it is lazy eager load that works after you get the result you can check the docs

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search