foreach()参数的类型必须是array|object,这是使用cookie时在Laraval 8中给定的字符串



我正在尝试创建一个在线书店,其中包括一个愿望列表,用户可以在其中存储书籍。我希望通过在Laravel中使用cookie来创建这个。

存储id似乎没有问题,但当我尝试检索它们并使用书籍的foreach循环显示列表时(在本例中是书籍的id(,我得到错误">foreach((参数的类型必须是array|object,string给定">

在心愿单控制器中设置cookie:

public function store($id)
{
Cookie::queue('wishlist', $id, 10);
$book = Book::query()->whereHas('bookCopies', function ($q) use ($id) {
$q->whereId($id);
})->first();
return redirect()->route('books.index', ['id' => $book->id]);
}

获取数据并在Wishlist Controller的视图中显示:

public function index()
{
if (Cookie::has('wishlist')) {
$books = Book::query()->whereHas('bookCopies', function ($q) {
$q->whereIn('id', Arr::flatten(Cookie::get('wishlist')));
})->get();
}
return response(view('member.wishlist', ['books' => $books ?? []]));
}

web.php中的路由:

Route::group([
'prefix' => 'wishlist',
'as' => 'wishlist'
], function () {

Route::get('index', [WishlistController::class, 'index'])->name('.index');
Route::post('store/{id}', [WishlistController::class, 'store'])->name('.store');
});

我如何将id发送到商店((:

@if($book->firstAvailableBookCopyId())
<form action="{{ route('wishlist.store', $book->firstAvailableBookCopyId()) }}" method="post">
@csrf
<button class="text-lg bg-gray-200 rounded-xl p-2 hover:bg-gray-300 cursor-pointer" type="submit" >Wishlist</button>
</form>
@else
Empty...
@endif

循环浏览wishlist.blade.hp:上的数据

@forelse($books as $book)                                                     
<tr>                                                                      
<td class="w-1/3 text-left py-3 px-3">{{ $book->title }}</td>         
<td class="w-1/3 text-left py-3 px-3">{{ $book->author->name }}</td>  
<td class="text-left py-3 px-3">{{ $book->genre->title }}</td>        
<td class="text-left py-3 px-3"><a                                    
href="{{ route('book.show', ['id' => $book->id] )}}">Open</a> 
</td>                                                                 
</tr>                                                                     
@empty                                                                        
<tr>                                                                      
<td>                                                                  
<p>Nothing to show...</p>                                         
</td>                                                                 
</tr>                                                                     
@endforelse                                                                   

实际上,此错误在Arr::flatten(Cookie::get('wishlist')辅助程序中,而不在刀片的@foreach循环中。因为Arr::flatten是接受多维数组转换为单个数组的。但是您试图传递一个愿望列表cookie值,该值实际上是一个整数或字符串。

因此,您需要将带有user_id的心愿单图书id作为心愿单表存储到数据库中,而不是保存在cookie中。

并进行此查询以获取愿望清单图书:

$wishlist = Wishlist::where('user_id', Auth::id())->pluck('id');
$books = Book::query()->whereHas('bookCopies', function ($q) {
$q->whereIn('id', $wishlist);
})->get();

最新更新