Почему я получаю эту ошибку: неопределенная переменная: product (View: C:\xampp\htdocs\basic\resources\views\mycart-да.лезвие.в PHP)?
Я новичок в Laravel здесь и при создании проекта у меня есть ошибки: неопределенная переменная: продукт (вид: C:\xampp\htdocs\basic\resources\views\mycart-да.лезвие.php) после проверки на ошибки, чтобы исправить все еще сохраняется, и я надеюсь, что вы, ребята, можете помочь мне. Заранее спасибо
блейд-код mycart:
@extends('layouts.app')
@section('content')
@if(Session::has('cart'))
<div class="container">
<b class="text-uppercase" style="color: darkgrey; font-size: 18px;">Item(s)</b>
<div class="row">
@foreach($products as $products)
<div class="col-sm-12 col-lg-2" style="padding-bottom: 12%;">
<div class="cart-item-container">
<a href="ads/{{strtolower(str_replace(" ","-",$product->name))}}"><div class="item-image"><img src="{{asset($product->image)}}" class="item-image">
</div>
<div class="item-tag" >
<p class="h5 text-capitalize">{{$product->name}}</p></a>
<p class="h4">GH¢ {{$product->price}}</p>
<div class="form-group" style="float: left; width: 25%;">
<select class="form-control" id="exampleFormControlSelect1">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
</select>
</div>
<div style="float: right;"><ul class="list-inline">
<li><a href="#" title="Save item for future use"><p class="text-primary text-capitalize"><span class="glyphicon glyphicon-heart-empty"></span></span></a></li>
<li><a href="#" title="Remove item from cart"><p class="text-muted text-capitalize"><span class="glyphicon glyphicon-trash"></span></p></a></li>
</ul>
</div>
</div>
</div>
</div>
@endforeach
</div>
<div style="float: right;"><ul class="list-inline">
<li><a href="#" title="Save item for future use"><p class="text-primary text-capitalize"><span class="glyphicon glyphicon-heart-empty"></span></span></a></li>
<li><a href="#" title="Remove item from cart"><p class="text-muted text-capitalize"><span class="glyphicon glyphicon-trash"></span></p></a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
@else
@endif
<div style="float: right; clear: both;">
<table class="table">
<tr>
<th scope="row">Total</th>
<td>GH¢ {{ $totalPrice }}</td>
</tr>
</table>
<ul class="list-inline">
<li><button class="btn btn-plain text-uppercase">contine shopping</button></li>
<li><button class="btn btn-primary text-uppercase">proceed to checkout</button></li>
</ul>
</div>
</div>
</div>
<hr style="border: 1px solid rgb(215,215,215); width: 85%;">
<div class="container" style="margin-top: 5%;">
<b class="text-uppercase" style="color: darkgrey; font-size: 18px;">saved item(s)</b>
<div class="row">
</div>
</div>
@endsection
И код контроллера ProductController:
<?php
namespace App\Http\Controllers;
use App\Item;
use Illuminate\Http\Request;
use App\Cart;
use App\Http\Requests;
use Session;
class ProductController extends Controller
{
public function addToCart(Request $request, $id)
{
$product = Item::find($id);
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$cart->add($product, $product->id);
$request->session()->put('cart', $cart);
return redirect()->route('welcome.index');
}
public function getCart()
{
if (!Session::has('cart')) {
return view('mycart');
}
$oldCart = Session::get('cart');
$cart = new Cart($oldCart);
return view('mycart', ['products' => $cart->items, 'totalPrice' => $cart->totalPrice]);
}
}




Ответы - Почему я получаю эту ошибку: неопределенная переменная: product (View: C:\xampp\htdocs\basic\resources\views\mycart-да.лезвие.в PHP)? / Why do I get this error : Undefined variable: product (View: C:\xampp\htdocs\basic\resources\views\mycart.blade.php)?

24.12.2019 09:23:30
В вашем getCart()
вы возвращаете продукты, если есть переменная сеанса для cart
. Однако, если нет переменной корзины сеанса, вы возвращаете представление без какой-либо переменной, прикрепленной здесь:
if (!Session::has('cart')) {
return view('mycart');
}
Чтобы исправить ошибку отсутствующей переменной в представлении Блейда, определите пустое значение $products
и верните его вместе с представлением из контроллера:
if (!Session::has('cart')) {
$products = [];
$totalPrice = 0;
return view('mycart', compact('products', 'totalPrice));
}
Примечание - у вас будет та же проблема с $totalPrice
поэтому я определил 0 для этой переменной, чтобы предотвратить ошибку.