2024-07-17 16:24:28 -07:00
< ? php
namespace App\Http\Requests ;
use App\Models\Accessory ;
use Illuminate\Support\Facades\Gate ;
class AccessoryCheckoutRequest extends ImageUploadRequest
{
/**
* Determine if the user is authorized to make this request .
*/
public function authorize () : bool
{
return Gate :: allows ( 'checkout' , new Accessory );
}
public function prepareForValidation () : void
{
if ( $this -> accessory ) {
2024-07-17 17:46:53 -07:00
$this -> diff = ( $this -> accessory -> numRemaining () - $this -> checkout_qty );
\Log :: debug ( 'num remaining in form request: ' . $this -> accessory -> numRemaining ());
\Log :: debug ( 'accessory qty in form request: ' . $this -> accessory -> qty );
\Log :: debug ( 'checkout qty in form request: ' . $this -> checkout_qty );
\Log :: debug ( 'diff in form request: ' . $this -> diff );
2024-07-17 16:24:28 -07:00
$this -> merge ([
2024-07-17 17:46:53 -07:00
'checkout_qty' => $this -> checkout_qty ,
'number_remaining_after_checkout' => ( $this -> accessory -> numRemaining () - $this -> checkout_qty ),
'number_currently_remaining' => $this -> accessory -> numRemaining (),
'checkout_difference' => $this -> diff ,
2024-07-17 16:24:28 -07:00
]);
2024-07-17 17:46:53 -07:00
\Log :: debug ( '---------------------------------------------' );
2024-07-17 16:24:28 -07:00
}
}
/**
* Get the validation rules that apply to the request .
*
* @ return array < string , \Illuminate\Contracts\Validation\ValidationRule | array < mixed >| string >
*/
public function rules () : array
{
return array_merge (
[
'assigned_to' => [
'required' ,
'integer' ,
'exists:users,id,deleted_at,NULL' ,
'not_array'
],
2024-07-17 17:46:53 -07:00
2024-07-17 16:24:28 -07:00
'number_remaining_after_checkout' => [
2024-07-17 17:46:53 -07:00
'min:0' ,
2024-07-17 16:24:28 -07:00
'required' ,
'integer' ,
],
2024-07-17 17:46:53 -07:00
2024-07-17 16:24:28 -07:00
'checkout_qty' => [
2024-07-17 17:46:53 -07:00
'integer' ,
'lte:qty' ,
'lte:number_currently_remaining' ,
'min:1' ,
2024-07-17 16:24:28 -07:00
],
],
);
}
public function messages () : array
{
2024-07-17 17:46:53 -07:00
$messages = [ 'checkout_qty.lte' => 'There are only ' . $this -> accessory -> qty . ' available accessories, and you are trying to check out ' . $this -> checkout_qty . ', leaving ' . $this -> number_remaining_after_checkout . ' (' . $this -> number_currently_remaining . ') accessories remaining (' . $this -> diff . ').' ];
2024-07-17 16:24:28 -07:00
return $messages ;
}
public function response ( array $errors )
{
return $this -> redirector -> back () -> withInput () -> withErrors ( $errors , $this -> errorBag );
}
}