Успешно вставлен в таблицу авторов и книг, но не может быть вставлен в сводную таблицу. Мне нужно вставить из одной и той же формы во все 3 таблицы. Я приложил скриншот всего моего кода. Просьба помочь.
Модель книги
class Book extends Model
{
protected $guarded = [];
public function authors(){
return $this->belongsToMany('App\Models\Author');
}
}
Автор Модель
class Author extends Model
{
public $guarded = [];
public function books(){
return $this->belongsToMany('App\Models\Book');
}
}
Контроллер книги
public function store(Request $request)
{
Book::create($this->validateBookInputs());
Author::create($this->validateAuthorInputs());
$book_id=Book::latest()->first()->id;
// $author_id=Author::latest()->first()->id;
// $book = new Book();
// $book->authors()->attach($author_id);
$author = new Author();
$author->books()->attach($book_id);
return back()->with('status', 'Insert Successful!');
}
public function validateBookInputs(){
return request()->validate([
'book_name' => 'required'
]);
}
public function validateAuthorInputs(){
return request()->validate([
'author_name' => 'required'
]);
}
Создание книги - просмотр
<form action="/books" method="POST">
<div class="form-group">
<label>Enter Book Name</label>
<input type="text" name="book_name" placeholder="Book Name" value="{{old('book_name')}}" class="form-control">
</div>
<div class="form-group">
<label>Enter Author Name</label>
<input type="text" name="author_name" placeholder="Author Name" value="{{old('author_name')}}"
class="form-control">
</div>
<button type="submit" class="button-green">Submit</button>
@csrf
создание таблицы авторов
public function up()
{
Schema::create('authors', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('author_name', '30');
$table->timestamps();
});
}
создать таблицу книг
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('book_name', '30');
$table->timestamps();
});
}
создать таблицу author_book
public function up()
{
Schema::create('author_book', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('author_id');
$table->unsignedBigInteger('book_id');
$table->timestamps();
});
}
Ошибка
Illuminate\Database\QueryException
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'author_id' cannot be null (SQL: insert into `author_book` (`author_id`, `book_id`) values (?, 25))