diff --git a/app/Http/Controllers/Api/V2/CustomerController.php b/app/Http/Controllers/Api/V2/CustomerController.php index 5a954bc..06f48b4 100644 --- a/app/Http/Controllers/Api/V2/CustomerController.php +++ b/app/Http/Controllers/Api/V2/CustomerController.php @@ -170,8 +170,8 @@ class CustomerController extends Controller try { /** @var \App\Models\Customer */ $customer = Customer::where('email', $request->email)->firstOrFail(); - /** @var \App\Models\CustomerLogin */ - $customerLogin = $customer->login($service->brand, Customer::FIRST_OR_FAIL); + $customer->loadBrandData($service->brand, true); + $customerLogin = $customer->logins->first(); } catch (ModelNotFoundException $e) { throw new ApiErrorException(ApiError::authFailed()); } diff --git a/app/Models/Customer.php b/app/Models/Customer.php index 87ad021..112f5d6 100644 --- a/app/Models/Customer.php +++ b/app/Models/Customer.php @@ -6,6 +6,7 @@ use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\ModelNotFoundException; class Customer extends Model { @@ -50,7 +51,7 @@ class Customer extends Model } $query = CustomerInfo::whereHas('brand', function (Builder $query) use ($brand) { $query->where('id', $brand->id); - })->whereHas('customer', function (Builder $query) use ($brand) { + })->whereHas('customer', function (Builder $query) { $query->where('id', $this->id); }); if ($firstOrNewOrFail === self::FIRST_OR_NEW) { @@ -111,9 +112,9 @@ class Customer extends Model * @param Brand $brand * @return self */ - public function loadBrandData(Brand $brand): self + public function loadBrandData(Brand $brand, bool $orFail = false): self { - return $this->load([ + $this->load([ 'logins' => function ($q) use ($brand) { $q->where('brand_id', $brand->id); }, @@ -121,6 +122,13 @@ class Customer extends Model $q->where('brand_id', $brand->id); } ]); + if ($orFail and !isset($this->relations['logins'][0])) { + throw (new ModelNotFoundException())->setModel(CustomerLogin::class); + } + if ($orFail and !isset($this->relations['infos'][0])) { + throw (new ModelNotFoundException())->setModel(CustomerInfo::class); + } + return $this; } /**