0
votes

My code is like this :

<?php
public function getFavoriteStore($param = null)
{
    $num = 20;
    $q = $param['q'];
    $location = $param['location'];

    $result = $this->store_repository->whereHas('favorites', function ($query) {
        $query = $query->where('stores.status', '=', 1)
              ->where('favorites.favoritable_type', 'like', 'App\\\Models\\\Store');
        if(isset($location))
           $query = $query->where('stores.address', 'like', "%$location%");

        if(isset($q)) {
            $query = $query->where(function ($query) use ($q) {
                $query->where('stores.name', 'like', "%$q%")
                      ->where('stores.address', 'like', "%$q%", 'or');
            });
        }

        return $query;
    })->paginate($num);

    return $result;
}

It works

But, condition if ( if(isset($location)) & if(isset($q)) ) does not works

It seems there are still wrong

Is there anyone who can help me?

I follow this tutorial : https://laravel.com/docs/5.3/eloquent-relationships#querying-relationship-existence

1
if(isset($location)) && if(isset($q))geckob
Don't forget to inject location and q into your first closuregeckob
@geckob, Ok. Thanks brosamuel toh

1 Answers

2
votes

You need to add use() in your first closure as:

public function getFavoriteStore($param = null)
{
    $num = 20;
    $q = $param['q'];
    $location = $param['location'];

    $result = $this->store_repository->whereHas('favorites', function ($query) use($q, $location) {
        $query->where('stores.status', '=', 1)
              ->where('favorites.favoritable_type', 'like', 'App\\\Models\\\Store');
        if(isset($location))
           $query->where('stores.address', 'like', "%$location%");

        if(isset($q)) {
            $query->where(function ($query) use ($q) {
                $query->where('stores.name', 'like', "%$q%")
                      ->where('stores.address', 'like', "%$q%", 'or');
            });
        }
    })->paginate($num);

    return $result;
}

And there is no need to assign and return the $query variable in your closure function.