dimanche 1 août 2021

check if record exist through relation in laravel

I have Product table:

id | title | price | user_id

Menu Planner Table:

id | day | category_id | product_id | user_id

Product Model:

class Product extends Model
{
    public function menuplanner()
    {
        return $this->belongsTo(MenuPlanner::class);
    }
    public function check($Catid,$productID,$userID,$day)
    {
        return $this->menuplanner()->select('product_id')->where('product_id', '=', $productID)->where('user_id', '=', $userID)->where('day', '=', $day)->first();
    }
}

MenuPlanner Model:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class MenuPlanner extends Model
{
    public function products()
    {
        return $this->hasMany('App\Models\Product');
    }
}

In Controller

$product = Product::where(['user_id'=>$ID])->get();
$menuPlanner=MenuPlanner::where(['user_id'=>auth()->user()->id,'category_id'=>$categoryID])->get(); 
$html =  view('frontend.available_items', ['products'=>$product,'day'=>$day,'partnerID'=>$partnerID,'categoryID'=>$categoryID,'menu_planner'=>$menuPlanner,'user_id'=>auth()->user()->id)->render();
echo json_encode(array('products' => $html)); 

Issue is in my view

i want to show all products that are returned from controller but want to replace button if product already exist in menuPlanner for that specific user, for that i'm using if($rowProducts->check($categoryID,$rowProducts->id,$user_id,$day)) condition

@foreach($products as $key=>$rowProducts)
if($rowProducts->check($categoryID,$rowProducts->id,$user_id,$day))

but this condition always return NULL.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire