Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

BaconJuice's avatar

Insert records to either two tables or one table depending on if a record exists or not using Laravel query builder

I'm trying to insert records to either two tables or one table depending on if a record exists or not.

First table Authors

    ID | Name
    1  | Joe
    2  | Sam

Second table Books

  ID | author_ID | Book
  1  | 2         | Book1
  2  | 2         | BookYYY
  3  | 1         | BookABC

What I want to accomplish is to check if author exists first, if not insert author and his book and if it DOES exists insert just the book with the right author ID

Here is what I've attempted so far that doesn't seem to work.

$result = DB::table('authors')
                ->where('name',  $data['author_name'])
                ->where('username', $data['author_username'])->pluck('id');
    
    if(is_null($result)){
        //Not in table add new author
        $id = DB::table('authors')->insertGetId(
            ['name' =>  $data['author_name'], 'username' => $data['author_username']]
        );
        //Add book
        DB::table('books')->insert(
            ['author_id' => '.$id.', 'name' => "Book777"]
        );
    }
    else{
        //Is in table insert just book
        DB::table('books')->insert(
            ['author_id' => '.$result.', 'name' => "Book777"]
        );
    }

So I'm trying to add author with Book name "Book777" but if author does exists in DB get the author ID and insert just the book.

Thank you all for helping me with this! Appreciate any help.

0 likes
1 reply
jlrdw's avatar

I would use empty instead of null in the above.

Please or to participate in this conversation.