1

i'm using laravel 5.2 and i need get the id of the newly created object in the same function in a controller to create another object with this attribute.

This is the function in the controller:

public function store(Request $request)
    {
        Movie::create([
            'usuario_id' => $request['usuario_id'],
            'asignatura_id' => $request['asignatura_id'],
            'name' => $request['name'],
            'visit' => $request['visit'],
            'language' => $request['language'],
        ]);

        Subtitle::create([
            'url' => $request['subtitle'],
            ]);
        return "OK";
    }

I need the id of this Movie to create a new Subtitle because the id is a foreign key in Subtitle. Thanks for the answers.

Bullgod
  • 149
  • 1
  • 3
  • 15
  • `$movie = Movie::create(...); echo $movie->id;` – ceejayoz Aug 01 '16 at 21:22
  • 2
    Possible duplicate of [Laravel, get last insert id using Eloquent](http://stackoverflow.com/questions/21084833/laravel-get-last-insert-id-using-eloquent) – ceejayoz Aug 01 '16 at 21:23

1 Answers1

2

You can get the Id by assigning the created object to a new variable.

public function store(Request $request)
{
    $movie = Movie::create([
             'usuario_id' => $request['usuario_id'],
             'asignatura_id' => $request['asignatura_id'],
             'name' => $request['name'],
             'visit' => $request['visit'],
             'language' => $request['language']
    ]);

    Subtitle::create(['url' => $request['subtitle']]);

    $movieId = $movie->id; //replace `id' with your real ColumnName. Same way you can retrieve all other Columns
    return "OK";
}
jonju
  • 2,711
  • 1
  • 13
  • 19