1

I am creating an interactive text form input using Livewire.

When the user types some characters into the text box I wish to return the filtered registrations from a table that has a hasMany relationship to the user.

In essence, the user hasMany cars. (although the key is creator_id, not user_id).

I am trying to do something along the lines of:

public function getSuggestions()
{
   $user = Auth::user();
   return $user->registrations->where('registration','like', '%' . $this->search . '%');
}

The user model contains the relationship:

public function registrations():HasMany
{
     return $this->hasMany(Registration::class,'creator_id');
}

When I just use the following without trying to filter the query...

return $user->registrations;

I get a collection of all registrations owned by the user, which is correct. it also calls the function to return the registrations each time I type a character, so Livewire is working correctly

However, I cannot work out how to alter the query, so the returned registrations are filtered on the like clause.

Karl Hill
  • 12,937
  • 5
  • 58
  • 95
DeveloperChris
  • 3,412
  • 2
  • 24
  • 39
  • potential doublicate of: https://stackoverflow.com/questions/38608244/laravel-eloquent-query-where-like-relationship – helle Jul 31 '23 at 03:52
  • Does this answer your question? [Laravel eloquent query where like relationship?](https://stackoverflow.com/questions/38608244/laravel-eloquent-query-where-like-relationship) – helle Jul 31 '23 at 03:52
  • Thanks @helle but I had seen that and it wasnt what I was looking for. – DeveloperChris Jul 31 '23 at 04:23
  • Remember that object magic property (i.e. `$user->registrations`) returns already formed collection, and object method (i.e. `$user->registrations()`) returns query builder which then can be chained to other methods. Like `$user->registrations()->where(['some' => $thing])->first()` or `$user->registrations()->where(['some' => $thing])->get()`. – Tpojka Jul 31 '23 at 17:53
  • @Tpojka I am relatively new to Laravel and didn't know this distinction. I assume in the code laravel is looking to see if there is a property or method that matches the name and runs some extra calls if its a property to turn it into a collection. – DeveloperChris Aug 02 '23 at 04:19

1 Answers1

1

Assuming you have the following relationship in your User model:

// User.php
public function registrations(): HasMany
{
    return $this->hasMany(Registration::class, 'creator_id');
}

You can modify the getSuggestions() method like this:

use Illuminate\Database\Eloquent\Collection;

public function getSuggestions(): Collection
{
    $user = Auth::user();

    // Use the where method on the relationship and apply the "like" filter
    return $user->registrations()->where('registration', 'like', '%' . $this->search . '%')->get();
}

Call get() to execute the query and retrieve the filtered registrations as a collection.

Karl Hill
  • 12,937
  • 5
  • 58
  • 95