Laravel 多对多检索图书&作者姓名错误拉雷维尔
无法将所有书籍名称和作者姓名显示为列表。获取错误。如果我在controllerindex方法中返回books和authors变量,我将以数组的形式获取数据。但无法在视图中访问它们。同样正如下面Book Controller中的注释代码所述,来自laravel文档的代码显示错误 图书模型 作者模型 图书管理员 View index.blade.phpLaravel 多对多检索图书&作者姓名错误拉雷维尔,laravel,many-to-many,Laravel,Many To Many,无法将所有书籍名称和作者姓名显示为列表。获取错误。如果我在controllerindex方法中返回books和authors变量,我将以数组的形式获取数据。但无法在视图中访问它们。同样正如下面Book Controller中的注释代码所述,来自laravel文档的代码显示错误 图书模型 作者模型 图书管理员 View index.blade.php 由于将$book设置为数组$books[]=$b->book_name;中的字符串,因此出现错误;。您不应该对控制器中的$books集合执行任何操作
由于将$book设置为数组$books[]=$b->book_name;中的字符串,因此出现错误;。您不应该对控制器中的$books集合执行任何操作,可以将其直接发送到视图 控制器: 查看一行,用逗号拆分作者: 查看循环,使用新行拆分作者:
非常感谢。第一个视图方法可以工作,但第二个视图显示此集合实例上不存在error-Property[authors]。
class Book extends Model
{
protected $guarded = [];
public function authors(){
return $this->belongsToMany('App\Models\Author')->withTimestamps();
}
}
class Author extends Model
{
public $guarded = [];
public function books(){
return $this->belongsToMany('App\Models\Book')->withTimestamps();
}
}
public function index()
{
$query = Book::with('authors')->get();
Pls Read the commented lines below -
//foreach ($query as $book) {
//return $book->authors->author_name; //Error: Property [author_name] does not exist on this collection instance.
//}
// (above code is given in laravel documentation but shows error : why?)
foreach($query as $b){
$books[] = $b->book_name;
$authors[] = $b->authors->first()->author_name;
}
return view('books.index', compact('books','authors'));
}
public function create()
{
return view('books.create');
}
public function store(validateAuthorBook $request)
{
$validated = $request->validated();
if($validated){
$book = new Book();
$book->book_name = $request->book_name;
$book->save();
$author = new Author();
$author->author_name = $request->author_name;
$author->save();
$book->authors()->attach($author);
}
return back()->with('status', 'Insert Successful!');
}
@foreach($books as $b)
<tr>
<th>{{$loop->iteration}}</th>
<td>{{$b->book_name}}</td>
//<td>how to get author name</td>
@endforeach
</tr>
Facade\Ignition\Exceptions\ViewException
Trying to get property 'book_name' of non-object (View:
D:\ProgrammingSSD\laragon\www\ulclibrary\resources\views\books\index.blade.php)
public function index()
{
$books = Book::with('authors')->get();
return view('books.index', compact('books'));
}
@foreach($books as $book)
<tr>
<td>{{ $loop->iteration }}</td>
<td>{{ $book->book_name }}</td>
<td>{{ $book->authors->pluck('author_name')->implode(', ') }}</td>
</tr>
@endforeach
@foreach($books as $book)
<tr>
<td>{{ $loop->iteration }}</td>
<td>{{ $book->book_name }}</td>
<td>
@foreach($book->authors as $author)
{{ $author->author_name }}<br/>
@endforeach
</td>
</tr>
@endforeach