I want to check if current user already has this car.
User.php:
public function car()
{
return $this->hasMany(Car::class);
}
Car.php
public function user()
{
return $this->belongsTo(User::class);
}
For example, I'm passing to view all cars from cars table and I want to check if current user already has this car:
@foreach( $cars as $car )
@if(Auth::user()->cars->where('car_id', $car->id)->exists())
You have this car!
@else
Buy this car!
@endif
@endforeach
Now, this code returns an error:
Call to a member function where() on null
How can I check if User already has this car?
2 Problems:
First the typo car
/cars
.
Second, you have public function car()
so it should be Auth::user()->car()->where('car_id', $car->id)->exists()
for condition chaining.
Check out the "One To Many" Section in Laravel 5.4 Documentation about chaining query conditions (pretty much at the end of the section).