3

I display an element randomly from my test table, so how can I get the id of this element:

$tests= DB::table('test')->inRandomOrder()->limit(1)->get();

because I want to compare it with an other id

1
  • DB::table('test')->inRandomOrder()->first()->getKey() Commented Jul 4, 2018 at 17:01

2 Answers 2

1

->get() returns a Collection or records from your test table. You need to use a loop to compare a single record's value:

$id = 1; // Or whatever you're comparing to
$tests = DB::table('test')->inRandomOrder()->limit(1)->get();
foreach($tests AS $test){ 
  dd($test->id == $id); 
}

Or simply use ->first() to return a single record from test:

$id = 1;
$test = DB::table('test')->inRandomOrder()->first();
dd($test->id == $id); 
Sign up to request clarification or add additional context in comments.

Comments

0

->get(); method return instance of \Illuminate\Database\Eloquent\Collection. For getting a single instance use ->first();method. See also official docs https://laravel.com/docs/5.5/queries#ordering-grouping-limit-and-offset
For example.

$test = DB::table('test')->inRandomOrder()->first();
if ($test->id == $id) {
    // your logic
}

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.