Laravel get attribute with hasMany
I'm making shop online with Laravel. I made Cart with records user_id and product_id with relations hasMany
to products. My problem is that I can't get for example product's name or price, I can only get whole array with products and cart data. Can someone tell me how to get it? Maybe there is a problem with a query or just view syntax.
My migration:
public function up()
{
Schema::create('carts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('product_id');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('product_id')->references('id')->on('products');
});
Here is my controller function:
public function index(Request $request)
{
$query = Cart::with('product')->where('carts.user_id', $request->user()->id);
$query = $query->get();
return view('cart.index', ['cart' => $query]);
}
And view to show cart
@extends('app')
@section('content')
@foreach ($cart as $item)
<form method="" action="">
<button class="btn btn-outline-dark">X</button>
</form>
@endforeach
@endsection
Model:
class Cart extends Model
{
use HasFactory;
public function product() {
return $this->hasMany(Product::class, 'id', 'product_id');
}
}
Is there another option for $item['product']
to get only product data?
Forgot to paste what view returns:
[{"id":10,"name":"lklkl","description":"klklkk","img":"przyklad.mo.jpg","price":50,"count":9,"created_at":"2022-05-24T13:13:03.000000Z","updated_at":"2022-05-24T13:13:03.000000Z"}]
I would like to get for example product's name.
Comments
Post a Comment