itai neil chiriseri
itai neil chiriseri

Reputation: 41

Sending Email After Saving Data to Database

Im trying to send an email from my laravel application after saving the data to the database from my controller. How I can do that?

Here is my code for saving the data. I want to send the email before it redirects to the /vehicle route

if($request->input('type_of_insurance') == 'third_party_insurance') {
    $motorVehicle = new MotorVehicle();
    $motorVehicle->Make = $request->input('car_make');
    $motorVehicle->Model = $request->input('car_model');
    $motorVehicle->Car_Value = $request->input('car_value');
    $motorVehicle->Year_Of_Manufacture = $request->input('car_year');
    $motorVehicle->Engine_Number = $request->input('engine_number');
    $motorVehicle->Chassis_Number = $request->input('chassis_number');
    $motorVehicle->Cubic_Capacity = $request->input('cubic_capacity');
    $motorVehicle->Type_Of_Insurance = $request->input('type_of_insurance');
    $motorVehicle->Stamp_Duty = $stampDuty;
    $motorVehicle->Standard_Fee = 50;
    $motorVehicle->Premium = $premium;
    $motorVehicle->save();

    return redirect('/vehicle')->with('message','Policy Approved');

Upvotes: 0

Views: 1058

Answers (1)

Soheil Rahmat
Soheil Rahmat

Reputation: 521

in this case, you can use an observer on your model or create one.


class MotorVehicleObserver
{
    public function created(Content $content){
        //this function will be called every time you insert new data on your database
        //your codes about sending the email will come here
    }
}

and for adding this observer to your model:


    protected static function boot()
    {
        parent::boot();
        self::observe(new MotorVehicleObserver);
    }

Or you can add the observer directly to your model like below:


   protected static function boot()
    {
        parent::boot();

        static::created(function (self $content){
            //this function will called every time you insert a new data on your database
            //your codes about sending email will come here
        });
    }

for more information, visit: Laravel Events

Upvotes: 2

Related Questions