1

I'm trying to query data from btween two date from my date column. I tested using api

http://127.0.0.1:8000/api/expense?start=2019-08-01&2019-08-04

but its give me all the records not from date range?

My Controller

  public function index(Request $request)
    {

        $user = auth()->user(); 

        $expenses = Expense::whereHas('user', function($subQuery) use($user){
            return $subQuery->where('shop_id', '=', $user->shop_id);
        })->with(['user'])->get();

        if($request->start && $request->end) {
            $expenses->where(function($q) use ($request) {
                $q->whereBetween('date', array($request->start, $request->end));
            });
        }

        return ExpenseResource::collection($expenses);

    }

i think i do something wrong with my Controller, but i cant still figure it out..

Thanks in advances...

13
  • try this : 127.0.0.1:8000/api/expense?start=2019-08-01&end=2019-08-04 Commented Aug 28, 2019 at 13:16
  • got this error "explode() expects parameter 2 to be string, object given" Commented Aug 28, 2019 at 13:18
  • where did you using explode() function? Commented Aug 28, 2019 at 13:18
  • like u see in my controller, im not using it.. Commented Aug 28, 2019 at 13:19
  • 1
    @SandeepSudhakaran its okay, bro now i solved it. Commented Aug 29, 2019 at 11:40

2 Answers 2

0

Hope this answer helps

public function index(Request $request)
{

    $user = auth()->user(); 

    $expenses = Expense::whereHas('user', function($subQuery) use($user){
        return $subQuery->where('shop_id', '=', $user->shop_id);
    })->with(['user']);

    if($request->start && $request->end) {
        $expenses->whereBetween('date', array($request->start, $request->end));
    }        
    return ExpenseResource::collection($expenses->get());

}

what you did was you get() the result first then you apply whereBetween(). Instead I applied whereBetween() first then if your if condition satisfied the get()

and change your URL to 127.0.0.1:8000/api/expense?start=2019-08-01&end=2019-08-04

Sign up to request clarification or add additional context in comments.

4 Comments

suddenly, it got another error Call to undefined method Illuminate\Database\Eloquent\Builder::mapInto()
made some edit in answer. in if clause. please try this one tooo
ok. made one more change in answer. return ExpenseResource::collection($expenses->get());
Thanks buddy. Happy coding
0

try something like this

$users = User::select("users.*")

            ->whereBetween('created', ['2018-02-01', '2018-02-10'])

            ->get();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.