简体   繁体   中英

foreach() argument must be of type array|object, string given in Laraval 8 when using cookies

I'm trying to make an online bookshop that includes a wishlist where users can store books. I wish to create this by using cookies in Laravel.

There seems to be no problem with storing the id's, but when I try to retrieve them and show a list using a foreach loop of the book (in this case the id's of the books) I get the error ' foreach() argument must be of type array|object, string given '

Setting the cookies in the Wishlist Controller:

    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]);
    }

Getting the data and showing it in the view in 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 ?? []]));
    }

Routes in 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');

});

How I send the id to the store():

@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

Looping through the data on wishlist.blade.php:

@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                                                                   

Actually, this error is in Arr::flatten(Cookie::get('wishlist') helper not in your blade's @foreach loop. BecauseArr::flatten is accept multi-dimension array to convert into a single array. But you are trying to pass a wishlist cookie value that is actually an integer or string.

So, you need to store wishlist book ids with user_id into the database as a wishlist table instead of saving in cookies.

And make this query to get the wishlist books:

$wishlist = Wishlist::where('user_id', Auth::id())->pluck('id');

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM