I want to insert multiple emails of a user into a different table in Laravel. Is it possible?
Here is code:
use App\PersonData;
class PersonDataController extends Controller
{
public function store(Request $request)
{
$user = new PersonData();
return PersonData::store($request->person_data,$user);
}
}
here is model
use App\CustomerEmail;
use App\SupplierEmail;
class PersonData extends Model
{
public function customeremails()
{
return $this->hasMany(CustomerEmail::class);
}
public function supplieremails()
{
return $this->hasMany(SupplierEmail::class);
}
public static function store($request,$user)
{
$user = fill($request);
$user->save();
return $user;
}
}
here is 2nd model where want to insert multiple emails
class CustomerEmail extends Model
{
protected $fillable = ['emails','person_data_id'];
public function persondata()
{
return $this->belongsTo(PersonData::class);
}
}
and final json code
{
"person_data": {
"first_name": "Customer",
"last_name": "customer_lastname",
"company_name": "new industry",
"gst_number": "no",
"type": "customer",
"customeremails": [
{
"person_data": 1,
"email": "relation@gmail.com"
}
],
"address": "house 123, city:ludhiana",
"phone_numbers": "8844845545",
"website": "www.google.com"
}
}
As I understood your question. what you are looking for is saveMany()
function for a one-to-many
relationship.
or may be i misunderstood your question
// first gather all the emails to be saved after 'person data' is saved.
// because 'customer email' needs 'person data' id.
$customer_emails = collect();
foreach($request->person_data->customeremails as $email) {
$cutomer_email = CustomerEmail::make([
'email' => $email.email
]);
$customer_emails->push($customer_email);
}
// save 'person data' first
$person_data = PersonData::create([
// your person_data
]);
// this will automatically set 'person_data' foreign key on the 'customer email' table
// and save
$person_data->customeremails()->savemany($customer_emails);