Creating records with relationship using author and book in laravel

In this post we will be creating records using relationship. For the sake of simplicity we will seed data for books and author by following this post and then we can proceed with this post as usual like below.

Back in BookController we have used two methods like below for creating single or multiple record with author hasMany books relation. We just need to make sure in Book and Author model mass assigment fields are set.

function createSingleRecord() {

	$authorName = 'Shayne Fisher IV';
	$bookTitle = 'Pride or Prejudice'; 

	$author = Author::firstOrCreate([ 'name'=> $authorName ]);

	$author->books()->create([
		'title' => $bookTitle
	]);

	dd('single book inserted');
}

Code above we have checked whether author is not created. If not then it is created with given author name. After that using has many books relation we are able insert single book record for that author in the books table in the database.

function createMultipleRecord() {

	$authorName = 'Shayne Fisher IV';
	$bookTitle = 'Pride or Prejudice,Digital fortress,deceiption point, inception'; 

	$titles = collect(explode(',',$bookTitle) )->map( function($record) {
		return ['title' => $record];
	});

	$author = Author::firstOrCreate([ 'name'=> $authorName ]);
	$author->books()->createMany($titles);

	dd('many books inserted');
} 

Code above we have checked whether author is not created like before. If not then it is created with given author name.

Since we are inserting multiple books this time for that author we have prepared array of array which is required pattern for createMany() method and it is done using collection methods collect() and map() methods.  Again has many relation is being used to insert book records for the author.

Related Posts