1

I currently have a function that simply creates a user record in the database

$user->name;
$user->address;
$user->save();

Once this is done, I've created an id for them in my users table.

I know I can return $user, but specifically how can I grab the id and name from that to be used in a call like so:

$user->save();

//return $user id and $user name
$update = new UpdateTable($id,$name);
Geoff_S
  • 4,917
  • 7
  • 43
  • 133
  • Duplicate of https://stackoverflow.com/questions/21084833/get-the-last-inserted-id-using-laravel-eloquent ? – paskl Mar 14 '19 at 19:11

2 Answers2

6

When you call $user->save(), the id (or primary key if it is not id) becomes available via $user->id. So, you'd simply pass the following to your UpdateTable() method:

$user = new User();

$user->name = "Test";
$user->address = "123 Somewhere";

$user->save();

$update = new UpdateTable($user->id, $user->name);
...
Tim Lewis
  • 27,813
  • 13
  • 73
  • 102
  • ok I tried that but it's not working. After the save, I'm dumping the user which gives objects with fillable, attributes, and original. Attributes and original both have the fields I need. – Geoff_S Mar 15 '19 at 16:31
  • `dd($user)` (dump and die) should only show 1 `User` model, not multiple objects. `attributes` and `original` are properties of the `Model`, which can be access via `$model->{attribute}`, or in this case `$user->id`, etc. When you say "but it's not working", what, *specifically* isn't working? Are you getting an error? – Tim Lewis Mar 15 '19 at 16:41
  • No error, but the update that I'm calling isn't actually updating. So as long as I'm doing it right from here, then I'll try again – Geoff_S Mar 15 '19 at 17:00
  • It's likely something inside your `UpdateTable` logic. After save, if you do a `dd($user->id)`, or `dd($user->name)` you should get a value. So, moving forward, if you experience a new problem, it's best to ask a new question. – Tim Lewis Mar 15 '19 at 17:13
  • Ah I realized after dumping them that the id is an int but the name is a string and I was passing both as strings – Geoff_S Mar 15 '19 at 17:35
0

Try this code

$user = User::create(['name' => 'name', 'address' => 'Some address']);
$update = new UpdateTable($user->id, $user->name);

or

$update = new UpdateTable($user->getPrimaryKey(), $user->name);
Davit Zeynalyan
  • 8,418
  • 5
  • 30
  • 55