A __construct on an Eloquent Laravel Model

前端 未结 2 895
有刺的猬
有刺的猬 2020-12-09 02:31

I have a custom setter that I\'m running in a __construct method on my model.

This is the property I\'m wanting to set.

    protected $         


        
2条回答
  •  情话喂你
    2020-12-09 03:06

    I wouldn't ever use a constructor in eloquent. Eloquent has ways to accomplished what you want. I would used a boot method with an event listener. It would look something like this.

    protected static function boot()
    {
        parent::boot();
    
        static::retrieved(function($model){
             $model->directory = $model->student_id ?? 'applicant_' . $model->applicant_id;
        });
    }   
    

    Here are all the model events you can use...

    • retrieved
    • creating
    • created
    • updating
    • updated
    • saving
    • saved
    • deleting
    • deleted
    • restoring
    • restored

提交回复
热议问题