mardi 27 avril 2021

Need to get data with laravel when query

I am trying to filter data using when query in Laravel, where it should filter data using the filter $sortBy or $categoryId. Please note the all 3 fields like $id $sortBy $categoryId are optional and will not be presented in all queries

public function Products(Request $request)
{
    $page     = $request->has('page') ? $request->get('page') : 1;
    $limit    = $request->has('itemsPerPage') ? $request->get('itemsPerPage') : 10;
    $sortBy = (($request->sortBy == "popularity")  ? "viewCount" : "created_at");
    $categoryId=  $request->get('categoryId');

    $sellerId = $request->header('id')?SellersBranding::findOrFail($request->header('id')):"Null";
    
    $productLive = ProductsLive::select('productTitle', 'product_id', 'brand_id', 'category_id')
        ->when($sellerId=="Null", function($query)  use ($page, $limit){
            return $query->where('status', 'active')
            ->limit($limit)->offset(($page - 1) * $limit);
        })
        ->when($sortBy, function ($query) use ($sortBy, $sellerId, $page, $limit){
            return $query->orderBy($sortBy, 'DESC')
                ->where('Sid', $sellerId->id)
                ->where('status','active')
                ->limit($limit)->offset(($page - 1) * $limit);
        })
        ->when($categoryId, function ($query) use ($categoryId, $sellerId, $page, $limit) {
            ->where('Sid', $sellerId->id)
                ->where(['category_id' => $categoryId, 'status' => 'active'])
                ->limit($limit)->offset(($page - 1) * $limit)
                ->inRandomOrder();
        })->get();
}

i am new in php and also in laravel please help how to get filtered data



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3eAnnMN
via IFTTT

Aucun commentaire:

Enregistrer un commentaire