D
D
Daniel2017-03-31 14:12:04
Laravel
Daniel, 2017-03-31 14:12:04

Laravel 5. How to correctly insert the id of the current insert into a table cell?

Good to everyone!
When adding a record to the table, you must insert the id of the current record into one of the cells. Is it possible to do this in one request? I have several options, but I do not know if they are correct.
Option 1:

$insert = Post::create([
                'name' => 'name',
                'text' => 'text'          
            ]);

$post = Post::find($insert->id);

$post->name( $post->name .  $insert->id);

$post->save();

Option 2:
$post = new Post();

$post->save();

$arr = array(
          'name' => 'name'  . $post->id,
          'text' => 'text'
 );

$post->fill($arr);
$post->save();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ramm, 2017-03-31
@rammtw

1. Pull out the id of the last post from the Post model
2. When creating a post, specify last_inserted_id + 1
Something like:

$lastId = Post::orderBy('id', 'DESC')->first()->id;

$post = Post::create([
    'name' => 'name' . $lastId+1,
    'text' => 'text'          
]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question