cleocoder
cleocoder

Reputation: 117

Get the last ID of recently created database row

I'm trying to pull the last inserted id from a database table so that I can input it into a new database table, like so:

$mealplaninput =
    MealPlanInput::create([
          'meal_type' => $meal,
          'suitable_for' => $suited,
          'allergens' => $allerg,
          'specific_allergen' => $spec,
          'no_of_people' => $nop,
          'start_date' => $request->date,
          'no_of_days' => $nod,
          'user_id' => $currentuserid,
      ]);

The attempt to pull the last id (but doesn't work):

$uniquemealplanid = $mealplaninput->id();

To then input into new table:

MealPlanDisplay::create([
      'MealPlan_ID' => $uniquemealplanid,
      'Day' =>  $recipeday,
]);

However I get the error:

Call to undefined method App\Models\MealPlanInput::id()

I have tried other methods too, like:

$uniquemealplanid =  $this->create($mealplaninput)->id;

But the error I get is:

Method App\Http\Controllers\MealPlanInputController::create does not exist.

How can I pull the last id from MealPlanInput?

Upvotes: 1

Views: 64

Answers (2)

Tayyab mehar
Tayyab mehar

Reputation: 621

You need to create an object from the model to get ID.

 $mealplaninput = new MealPlanInput;
    $mealplaninput->meal_type = $meal;
    $mealplaninput->suitable_for = $suited;
    $mealplaninput->allergens = $allerg;
    $mealplaninput->specific_allergen = $spec;
    $mealplaninput->no_of_people = $nop;
    $mealplaninput->start_date = $request->date;
    $mealplaninput->no_of_days = $nod;
    $mealplaninput->user_id = $currentuserid;
    $mealplaninput->save();  
    
    $uniquemealplanid = $mealplaninput->id;
    
       

Upvotes: 1

Vahid Marali
Vahid Marali

Reputation: 136

you need to try

$uniquemealplanid = $mealplaninput->id;

insted of

$uniquemealplanid = $mealplaninput->id();

Upvotes: 1

Related Questions