Files

126 lines
4.7 KiB
PHP

<?php
namespace App\Http\Livewire\Profile;
use App\Models\Admin;
use App\Models\Bank;
use App\Models\Organization;
use App\Models\User;
use Illuminate\Support\Facades\Storage;
use Livewire\Component;
class SelectMultipleProfiles extends Component
{
public $label = '';
public $placeholder = '';
public $typesAvailable = [];
public $eventName = 'selectedProfiles';
public $search = '';
public $searchResults = [];
public function mount()
{
$this->placeholder = implode(', ', array_map(function ($class) {
return __(strtolower(class_basename($class)));
}, $this->typesAvailable));
}
public function selectProfile($value)
{
$profile = collect($this->searchResults)->firstWhere('id', $value);
if (!$profile) {
return;
}
$this->dispatch($this->eventName, profiles: $profile);
$this->search = '';
$this->searchResults = [];
}
public function updatedSearch($newValue)
{
if (strlen($newValue) <= 2) {
$this->searchResults = [];
return;
}
$search = $newValue;
$results = collect();
$locationRelations = ['locations.city.translations', 'locations.district.translations', 'locations.division.translations'];
foreach ($this->typesAvailable as $type) {
if ($type === User::class) {
$results = $results->merge(
User::where('name', 'like', '%' . $search . '%')
->with($locationRelations)
->limit(6)->get()
->map(fn($item) => [
'id' => $item->id,
'type' => User::class,
'name' => $item->name,
'description' => '',
'location' => $item->getLocationFirstShort(),
'profile_photo_path' => url(Storage::url($item->profile_photo_path)),
])
);
}
if ($type === Organization::class) {
$results = $results->merge(
Organization::where('name', 'like', '%' . $search . '%')
->with($locationRelations)
->limit(6)->get()
->map(fn($item) => [
'id' => $item->id,
'type' => Organization::class,
'name' => $item->name,
'description' => __('Organization'),
'location' => $item->getLocationFirstShort(),
'profile_photo_path' => url(Storage::url($item->profile_photo_path)),
])
);
}
if (class_exists('App\\Models\\Bank') && $type === Bank::class) {
$results = $results->merge(
Bank::where('name', 'like', '%' . $search . '%')
->with($locationRelations)
->limit(6)->get()
->map(fn($item) => [
'id' => $item->id,
'type' => Bank::class,
'name' => $item->name,
'description' => __('Bank'),
'location' => $item->getLocationFirstShort(),
'profile_photo_path' => url(Storage::url($item->profile_photo_path)),
])
);
}
if (class_exists('App\\Models\\Admin') && $type === Admin::class) {
$results = $results->merge(
Admin::where('name', 'like', '%' . $search . '%')
->with($locationRelations)
->limit(6)->get()
->map(fn($item) => [
'id' => $item->id,
'type' => Admin::class,
'name' => $item->name,
'description' => __('Admin'),
'location' => $item->getLocationFirstShort(),
'profile_photo_path' => url(Storage::url($item->profile_photo_path)),
])
);
}
}
$this->searchResults = $results->take(6)->values()->all();
}
public function render()
{
return view('livewire.profile.select-multiple-profiles');
}
}