This issue related to the timing
When the constructor is being called in relation to the assignment of the $this->dealer_id
property. When constructor is called then object is instantiated, but at that point, the properties of the object haven't been assigned values yet.
In Laravel's form requests, the constructor is typically called before the request data is bound to the object's properties. So you're getting null
for $this->dealer_id
inside the constructor.
You can consider using the boot()
method instead of the constructor. The boot()
method is automatically called by Laravel after the request object has been created and the request data has been bound to its properties.
you can update you code:
class CreateLeadRequest extends FormRequest
{
private $dealer;
public function boot()
{
$this->dealer = Dealer::findOrFail($this->dealer_id);
parent::boot();
}
// ........ rest of your code
}
By moving your logic to the boot()
method, you ensure that $this->dealer_id
has been assigned a value before you try to retrieve the Dealer
instance.