Dev
Dev

Reputation: 6710

Laravel 5.2 eloquent returns soft deleted records

I am using Laravel 5.2.

I have a model as below:

<?php

namespace App\Models;
use Illuminate\Database\Eloquent\SoftDeletes;

class ZoomMeeting extends BaseModel {

    public $timestamps=true;        

    protected $table = 'zoom_meetings';

    use SoftDeletes;

    protected $dates = ['deleted_at'];

    protected $fillable = ['user_id', 'uuid', 'meeting_id', 'host_id', 'topic', 'status', 'type', 'start_url', 'join_url', 'created_at'];

    public function users() {
        return $this->belongsTo('App\Models\User');
    }
}

And the base model is as below:

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Auth;
use Carbon\Carbon;

class BaseModel extends Model {

    public $timestamps = false;

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

            static::creating(function($model) {
                if(empty($model->created_at))
                {
                    $model->created_at = date('Y-m-d H:i:s');
                }
                return true;
            });

            static::updating(function($model) {
            $model->updated_at = date('Y-m-d H:i:s');
            return true;
            });
     } 
}

I am using softdeletetrait in ZoomMeeting model, and soft deleting is working fine.

However, if I fetch records from the same model using eloquent, it returns the soft deleted records too. I am using code below to get the records:

$record = ZoomMeeting::where("user_id", $user_id)->where("meeting_id", $meeting_id)->orderBy("id", "DESC")->first();

The eloquent is building the query as:

select * from `zoom_meetings` where `user_id` = 3 and `meeting_id` = 707070707 order by `id` desc limit 1

See, there is no deleted at is null set in where statement. It is not preventing the deleted records.

I am not sure where am I making mistake?

Upvotes: 2

Views: 1338

Answers (1)

nerdoza
nerdoza

Reputation: 924

It looks like you are overriding the boot method, but you aren't ever actually calling the parent boot method (it's commented out), so the trait is never getting initialized correctly. I believe that also means the data you have been deleting is actually being deleted from the database.

Is there a reason you need to override the boot method? What you are adding is already done handled by the framework, so it doesn't appear to be necessary.

Upvotes: 6

Related Questions