dimanche 30 décembre 2018

How to get last inserted non incremental id using eloquent in Laravel?

I have two models Customer and Address. My Customer has non incremental primary key and is of type string which is "customer_id". The relationship between these two models is of one to many, that means for single customer many addresses for example invoice address, delivery address, current address, etc. My Customer model is as shown below

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    protected $keyType='string';
    protected $primaryKey='customer_id';
    public $incrementing=false;

    public function addresses()
    {
        return $this->hasMany('App\Address','customer_id');
    }
}

And my Address model is as shown below

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Address extends Model
{
    //
    public $timestamps = false;
    // protected $table="addresses";
    public function customer()
    {
        return $this->belongsTo('App\Customer');
    }
}

The other thing to note is that my "customer_id" is incremental in sense that I have created separate table namely customer_sequence which is auto incremental and before inserting record I append it with two character code using trigger and then place it into my "customers" table. Now when I save the data of customer and try to get id from customer model it returns me null. My controller is as shown below

public function store(Request $request)
{
$customer=new Customer;
$invoiceAddress=new Address;
$deliveryAddress=new Address;

$customer->name=$request->name;
$customer->type=$request->type;
$customer->dob=$request->dob;
$customer->save();

$deliveryAddress->street_name_no=$request->street_name_no;
$deliveryAddress->city=$request->city;
$deliveryAddress->country=$request->country;

//This throws error customer_id cannot be null integrity constraint
$deliveryAddress->customer_id=$customer->customer_id;
$deliveryAddress->save();
}



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2GJNjIg
via IFTTT

Aucun commentaire:

Enregistrer un commentaire