Cohchi
Cohchi

Reputation: 563

Laravel 8 how to replicate and get id of new model

I'm using laravel and I would like to replicate some data. So I did that :

$id = $request->id;
$data = Setting::find($id);
$newSetting = $data->replicate()->save();

But how to get the id of $newSetting ? to save that return's only true and I need to return my new id. I tried with push in place of save but that also return's true. I checked the documentation but I couldn't find it.

Can somebody help me please ?

Thanks in advance.

Upvotes: 1

Views: 3116

Answers (3)

Who Do You think am i
Who Do You think am i

Reputation: 455

you just have to :

$id = $request->id;
$data = Setting::find($id);
// now replicate data and save
$newData = $data->replicate();
//save the new data
$newData->save();
//get the new id
$newId = $newData->id;

Upvotes: 2

Rilwanu Isyaku
Rilwanu Isyaku

Reputation: 1

Here is the breakdown of how you can duplicate your record(instance) by using replicate() eloquent method:

  1. Using find():

        $id = $request->id;
        $post = Post::find($id);
        $duplicated_post = $post->replicate();
    
        //you can update some fields, like:
        $duplicated_post->user_id = '2'; // newly id
        $duplicated_post->save();
    
  2. Using where() clause:

        $id = $request->id;
        $post = Post::where('id', $id)->first();
        $duplicated_post = $post->replicate();
        //you can update some fields, like:
        $duplicated_post->user_id = '2'; // newly id
        $duplicated_post->save();
    
  3. Duplicate a relational model:

        $id = $request->id;
        $post = Post::find($id);
        $duplicated_post = $post->replicate();
        $duplicated_post->save();
    
        // duplicate a user in this instance:
        $original_user = $post->users; // 'users' is the relationship between user and the post
        $new_user = $original_user->replicate();
        $new_user->name = 'John Doe'; // if you want update a name
        $new_user->save();
    

Upvotes: 0

deltasystem123
deltasystem123

Reputation: 1

Can do this:

    $id = $request->id;
    $data = Setting::find($id);
    // replicate
    $replicatedData = $data->replicate();
    // get convert the model collection to array
    $arrayReplicatedData $replicatedData->toArray();
    //save it with the create method
    $newCreatedModel = Setting::create($arrayReplicatedData);
    // Get the new id
    $newId = $newCreatedModel->id;

Upvotes: 0

Related Questions