0
votes

I have a draw system on my site. There are 2 draws in the database now, but for some reason, only the last created draw is displayed on the draw page. My code is:

public function raffling()
{
    parent::setTitle('Items raffling | ');
    $green_ticket = \DB::table('users')->where('id', $this->user->id)->value('green_ticket');

    $kolvo=\DB::table('giveaway_items')->where('status',0)->orderBy('id', 'desc')->count();
    $giveaway = Giveaway::orderBy('id', 'desc')->first();
    $giveaway_users = \DB::table('giveaway_users')
        ->where('giveaway_id', $giveaway->id)
        ->join('users', 'giveaway_users.user_id', '=', 'users.id')
        ->get();
    $giveAway = Giveaway::where('winner_id', '!=', 'NULL')->orderBy('created_at', 'DESC')->first();
    $user = User::find($giveAway->winner_id);
    $username = $user->username;
    $userava = $user->avatar;
    $usersteamid = $user->steamid64;


    return view('pages.raffling', compact('kolvo', 'giveaway', 'giveaway_users', 'giveAway', 'user', 'username',
                                         'userava', 'usersteamid', 'green_ticket'));

}

I tried make changes at $giveaway = Giveaway::orderBy('id', 'desc')->first(); and instead of first() use take(2), but i received error Undefined property: Illuminate\Database\Eloquent\Builder::$winner_id. And the same error appears if I add take(2) to the line $giveAway = Giveaway::where('winner_id', '!=', 'NULL')->orderBy('created_at', 'DESC')->first(); instead of first().

Where is my problem, how i can fix this error?

3

3 Answers

1
votes

When you have used first() method means only one records retrieve.

Now as you said you want two records from the database. There are two methods available here.

1) take()

$giveaway = Giveaway::orderBy('id', 'desc')->take(2)->get();

2) limit()

$giveaway = Giveaway::orderBy('id', 'desc')->limit(2)->get();

*Your problem occurs because you have not used the get() method.

1
votes

take() is a method that is available on collections not the query builder. You need to get a collection from the query builder first and then use the method on that.

$giveAway = Giveaway::where('winner_id', '!=', 'NULL')
    ->orderBy('created_at', 'DESC')
    ->get()
    ->take(2);
1
votes

use take(2)

$giveaway = Giveaway::orderBy('id', 'DESC')->take(2)->get();