POV
POV

Reputation: 12005

How to show SQL query formed by ::create Laravel?

Is it possible to display a ready formed SQL after operation:

 $r = \App\Visitor::create($item);

Where $item is array data.

I wonder why this operation returns in $r inserted model, but there is no changes in db table.

So, thanks for answers I tried yours solutions:

This is query:

insert into `visitors` (`lastname`, `firstname`, `middlename`, `birthday`, `company`, `document_number`, `pincode`, `code`, `idEvent`) values ("Huse", "Huseynkhanov", "Akif", "1981-04-09", "XXX", 16428285, "QT0FE12", 19283746564923, "17");

This is screen of binding:

enter image description here

If execute query above in database it works. But Laravel does not insert data.

Model is:

class Visitor extends Model
{
    public $timestamps = false;

    public $table = 'visitors';

    protected $fillable = [
        "lastname",
        "firstname",
        "middlename",
        "birthday",
        "company",
        "document_number",
        "pincode",
        "status",
        "code",
        "idEvent"
    ];

    protected $primaryKey = 'idVisitor';

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

        static::addGlobalScope(new StatusScope);
    }
}

Code is:

foreach ($items as $item) {
    \App\Visitor::create($item);
}

Upvotes: 0

Views: 101

Answers (2)

Davit Zeynalyan
Davit Zeynalyan

Reputation: 8618

You can use this

DB::enableQueryLog();
\App\Visitor::create(['key' => 'value', ....]);
$data = DB::getQueryLog();
$query = str_replace(array_fill(0, count($data[0]['bindings']), '?'), $data[0]['bindings'],  $data[0]['query']);
dd($query);

Upvotes: 1

Benjamin Beganović
Benjamin Beganović

Reputation: 1158

I believe, you can do something like this:

$r = \App\Visitor::create($item)->toSql();
dd($r);

Upvotes: 2

Related Questions