Hamza Dastgir
Hamza Dastgir

Reputation: 165

Condition checking in laravel api and getting result as json Response

This is my Laravel API which returns json response of Quizzes with 'status' = active.

Route::get('/quizzes', function() {
 $quizzes = App\Quiz::where('status', 'active')
            ->take(20)->get();

Here i am creating another variable $newquiz for returning only newer quizzes,BUT actually i dont need it , i wants to show responce with in my fields , i mean i wants to pass a flag $new which indicates new quizes within my $quizzes variable. how can i pass the flag to indicate newer quizzes ?

 $newquiz = DB::table('quiz')->select('id')
        ->where('created_at', '>', Carbon::now()->subDays(10))->get();


   return Response::json(array(
        'error' => false,
        'newquiz'=> $newquiz,
        'quizzes' => $quizzes,
        'status_code' => 200
    ));

Upvotes: 0

Views: 904

Answers (2)

Rajarathinam
Rajarathinam

Reputation: 11

$quizzes = App\Quiz::select(
                            'id',
                            '..',
                            DB::raw('created_at >= DATE_SUB(CURDATE(),INTERVAL 10 day) as isNew')
                        )->where('status', 'active')->take(20)->get();

Now you can access isNew field which have 1 or 0.

Hope it will helps you...

Upvotes: 1

aaron0207
aaron0207

Reputation: 2333

$newquiz = $newquiz ->each(function ($item, $key) {
    $item->new = true;
});

$quizzes = $quizzes->merge($newquiz)

Now you can check for $quizz->new

Upvotes: 1

Related Questions