1

Using Laravel scout I want to delete a record (on an Agent model), everything works well except that I'm redirecting to a list of agents after the delete, and since the queue is yet to be processed the deleted agent comes back from Meilisearch, but the Eloquent model doesn't exist anymore, resulting in an error Attempt to read property "id" on null :

// getting agents to display in the view
Agent::search($this->search)
    ->orderBy('id', 'asc')
    ->paginate($this->perPage)

// showing an agent ID in a loop in the view
{{ $agent->user->id }}

If reloading the page the list is fine - the deleted user has successfully been deleted. How can I prevent this error?

Jeremy Belolo
  • 4,319
  • 6
  • 44
  • 88

1 Answers1

2

It surprises me that scout contains the null values in the collection...

However, you can run a ->filter() (docs) on the returned collection to remove all null results in it:

Agent::search($this->search)->get()->filter();

The collection now does not contain any null values

Patrick Schocke
  • 1,493
  • 2
  • 13
  • 25
  • Hi, not a bad idea, although since I'm using `paginate` and not `get` I'm not sure how it would work... – Jeremy Belolo Apr 05 '22 at 06:11
  • 1
    Hey, sorry for my late reply. You could filter through your items and pass it to the view as seperate variable. Not ideal, but the best I can come up with on the spot. `$items = Agent::search($this->search)->paginate()->items()->filter()` – Patrick Schocke Apr 12 '22 at 19:19
  • 1
    Alternatlively (this is faster) you could just check in your view: `@if($agent->id)` – Patrick Schocke Apr 12 '22 at 19:21
  • Yeah I ended up doing something close, and indeed it's unsatisfying. Posted another question about it there : https://stackoverflow.com/questions/71751485/laravel-scout-queue-lag - fur this question since it was not clear enough your answer seems valid to me – Jeremy Belolo Apr 13 '22 at 14:39