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
->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);
->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
}
DB::table('test')->inRandomOrder()->first()->getKey()