'Laravel belongsto

what i want to do, Checking if "advert_id - auht user id" is in favorite table.
How should the query be?

Advert Table:
| id | name | | -------- | -------- | | 1 | lorem ipsun| | 2 | lorem ipsum dolor|

Favorite Table:
| id | user_id | advert_id| | -------- | -------- | -------- | | 1 | 1| 1 | | 2 | 1| 2 |

Advert Model :

class Advert extends Model
{
    protected $fillable = [
        "id",
        "name",
    ];
}

Favorite Model :

class Favorite extends Model
{
    protected $fillable = [
        'user_id',
        'advert_id'
    ];
}

Controller:

$adverts = Adverts::get();
return view("adverts", ["adverts" => $adverts]);

View:

@foreach ($adverts as $advert)
    @if ($advert->favorite == true)
       checked
    @else
       unchecked
    @endif
@endforeach

Fixed :

public function favorite(){
    return $this->belongsTo(Favorite::class, 'id', 'advert_id');
}
$adverts->withCount(['favorite as favorite' => function($q){
    $q->where("user_id", Auth::user()->id);
}]);


Solution 1:[1]

I believe you're trying to know if an advert has an associated favorite model right? In that case, you should define a relationship in the Advert model class that creates a link between a Favorite model and the Advert model:

// app/Models/Advert.php
public function favorites()
{
    return $this->hasMany(Favorite::class);
}

Then in your view file:

@foreach ($adverts as $advert)
    @if (count($advert->favorites))
       checked
    @else
       unchecked
    @endif
@endforeach

But if you're checking the adverts depending on whether the current user has favorited it then you should also do:

// app/Models/Advert.php
public function isFavoriteOfUser(User $user)
{
    return !! $this->favorites->where('user_id', $user->id)->first();
}

Then in your blade file you'd do:

@foreach ($adverts as $advert)
    @if ($advert->isFavoriteOfUser(auth()->user()))
       checked
    @else
       unchecked
    @endif
@endforeach

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Praise Dare