Laravel query. Where unique - php

I got database table like this:
**job_id**
5
5
5
6
6
7
8
8
I want to write query, which could select only unique id's. By saying unique I mean select only these values once:
5, 6, 7, 8
Thanks in advance!

You could use DISTINCT.
DB::table('table')->select('job_id')->distinct()->get();

How about:
$jobs = DB::table('my_job_table')
->groupBy('job_id')
->get();
Eloquent:
First, you need a model. You could generate this by using php artisan. php artisan make:model jobs (I assume you have done this already) This will create a model in /your_project/app/Job.php
Now you can use Eloquent (here in a route, to see some output):
Route::get('/jobs', function () {
$jobs = \App\Job::groupBy('job_id')->get();
return $jobs->lists('job_id');
});
will return something like: [0,1,3,4] instead of [0, 1, 1, 1, 3, 4, 4, 4].

Related

Loop and sum array Laravel 8

does anyone know how to loop an array & sum it? So i have an array with 3 values like in the picture below
and this is my code
use laravel collection sum() method instead of getting sum of array value in loop
collect([1, 2, 3])->sum();
or use php array_sum() method
array_sum([1, 2, 3, 4, 5]);

How do I chain multiple where and orWhere clause in laravel from an Array [duplicate]

This question already has answers here:
Query Laravel Select WhereIn Array
(2 answers)
Can I do Model->where('id', ARRAY) multiple where conditions?
(8 answers)
How to use multiple OR,AND condition in Laravel queries
(5 answers)
Closed 10 months ago.
I have an array
$user_lgas = ['lga1', 'lga2', 'lga3', ...];
I want to write a scopeSearch to get records base on user lgas
something like
$query->where('lga', $user_lgas[0])->orWhere('lga', $user_lgas[1])->orWhere('lga', $user_lgas[2]) ...
I want to generate this query dynamically from the array, but the logic is kind of complicated for me. Please any Help
As per the Laravel Documentation you should be able to use whereIn() or whereNotIn() with an array.
$users = DB::table('users')
->whereIn('id', array(1, 2, 3))->get();
$users = DB::table('users')
->whereNotIn('id', array(1, 2, 3))->get();
So for your example
$query->whereIn('lga',$user_lgas)->get();
For more details see: Database: Query Builder
You can just use a whereIn instead.
$query->whereIn('lga', $user_lgas)

Grouping multiple where clauses with OR in Laravel on one single orWhere function

I want to select from the database something like: SELECT * FROM database WHERE id=1 OR id=2 OR id=5;
I do not know the number of the where clauses that the user will request, it can be one, it can be 10.
I tried using Model::orWhere([['id','=',1],['id','=',2],['id','=',5]]) but it seems to be returning an empty list.
In the Laravel documentation, there is this example for the WHERE clause:
users = DB::table('users')->where([
['status', '=', '1'],
['subscribed', '<>', '1'],
])->get();
While the WHERE clause it working as in the example, orWhere clause doesn't seem to work like this though.
Following on from my comment you can us an IN Clause could solve this.
$model = Model::whereIn('id', array(1, 2, 3))->get();
Reference How to Make Laravel IN clause
Use something like:
User::whereIn('id', [1, 2, 3])->get();
As second parameter you need to use an array.

laravel query php how to get max value within a range

hello how do i get the max value of scores, where column ID range starts at 3-5
example table
I want to get the max value of scores, where column ID ranging from 3-5
, please help,
what I have done so far:
$max_scores_table= DB::table('scores_table')
->where('id', '>', 2)
->max('score');
another problem is when i have a decimal points in the table
when I used the max() function it gets the ID=5, which has a Score of 4.5, instead of ID=4 with a value of 4.6, tnx in advance
Try to use whereBetween hope this works:
$max_scores_table= DB::table('scores_table')
->select(DB::raw('MAX(score) FROM scores_table as MaxScore'))
->whereBetween('id', array(3,5))
->where('score', 'MaxScore')
->get();
OR:
$max_scores_table= DB::table('scores_table')
->whereBetween('id', array(3,5))
->max('score')
->get();
Write query as below:
$max_scores_table = DB::table('scores_table')
->whereBetween('id',array(3,5))
->max('score');
Reference: Laravel API
Use query like this
$max_scores_table = DB::table('scores_table')
->whereBetween('id', array(3, 5))->max('score')->get();
For your reference just follow Laravel Documentation

Laravel - Eloquent or Fluent random row

How can I select a random row using Eloquent or Fluent in Laravel framework?
I know that by using SQL, you can do order by RAND(). However, I would like to get the random row without doing a count on the number of records prior to the initial query.
Any ideas?
Laravel >= 5.2:
User::inRandomOrder()->get();
or to get the specific number of records
// 5 indicates the number of records
User::inRandomOrder()->limit(5)->get();
// get one random record
User::inRandomOrder()->first();
or using the random method for collections:
User::all()->random();
User::all()->random(10); // The amount of items you wish to receive
Laravel 4.2.7 - 5.1:
User::orderByRaw("RAND()")->get();
Laravel 4.0 - 4.2.6:
User::orderBy(DB::raw('RAND()'))->get();
Laravel 3:
User::order_by(DB::raw('RAND()'))->get();
Check this article on MySQL random rows. Laravel 5.2 supports this, for older version, there is no better solution then using RAW Queries.
edit 1: As mentioned by Double Gras, orderBy() doesn't allow anything else then ASC or DESC since this change. I updated my answer accordingly.
edit 2: Laravel 5.2 finally implements a wrapper function for this. It's called inRandomOrder().
This works just fine,
$model=Model::all()->random(1)->first();
you can also change argument in random function to get more than one record.
Note: not recommended if you have huge data as this will fetch all rows first and then returns random value.
tl;dr: It's nowadays implemented into Laravel, see "edit 3" below.
Sadly, as of today there are some caveats with the ->orderBy(DB::raw('RAND()')) proposed solution:
It isn't DB-agnostic. e.g. SQLite and PostgreSQL use RANDOM()
Even worse, this solution isn't applicable anymore since this change:
$direction = strtolower($direction) == 'asc' ? 'asc' : 'desc';
edit: Now you can use the orderByRaw() method: ->orderByRaw('RAND()'). However this is still not DB-agnostic.
FWIW, CodeIgniter implements a special RANDOM sorting direction, which is replaced with the correct grammar when building query. Also it seems to be fairly easy to implement. Looks like we have a candidate for improving Laravel :)
update: here is the issue about this on GitHub, and my pending pull request.
edit 2: Let's cut the chase. Since Laravel 5.1.18 you can add macros to the query builder:
use Illuminate\Database\Query\Builder;
Builder::macro('orderByRandom', function () {
$randomFunctions = [
'mysql' => 'RAND()',
'pgsql' => 'RANDOM()',
'sqlite' => 'RANDOM()',
'sqlsrv' => 'NEWID()',
];
$driver = $this->getConnection()->getDriverName();
return $this->orderByRaw($randomFunctions[$driver]);
});
Usage:
User::where('active', 1)->orderByRandom()->limit(10)->get();
DB::table('users')->where('active', 1)->orderByRandom()->limit(10)->get();
edit 3: Finally! Since Laravel 5.2.33 (changelog, PR #13642) you can use the native method inRandomOrder():
User::where('active', 1)->inRandomOrder()->limit(10)->get();
DB::table('users')->where('active', 1)->inRandomOrder()->limit(10)->get();
You can use:
ModelName::inRandomOrder()->first();
it's very simple just check your laravel version
Laravel >= 5.2:
User::inRandomOrder()->get();
//or to get the specific number of records
// 5 indicates the number of records
User::inRandomOrder()->limit(5)->get();
// get one random record
User::inRandomOrder()->first();
or using the random method for collections:
User::all()->random();
User::all()->random(10); // The amount of items you wish to receive
Laravel 4.2.7 - 5.1:
User::orderByRaw("RAND()")->get();
Laravel 4.0 - 4.2.6:
User::orderBy(DB::raw('RAND()'))->get();
Laravel 3:
User::order_by(DB::raw('RAND()'))->get();
In Laravel 4 and 5 the order_by is replaced by orderBy
So, it should be:
User::orderBy(DB::raw('RAND()'))->get();
For Laravel 5.2 >=
use the Eloquent method:
inRandomOrder()
The inRandomOrder method may be used to sort the query results randomly. For example, you may use this method to fetch a random user:
$randomUser = DB::table('users')
->inRandomOrder()
->first();
from docs: https://laravel.com/docs/5.2/queries#ordering-grouping-limit-and-offset
You can also use order_by method with fluent and eloquent like as:
Posts::where_status(1)->order_by(DB::raw(''),DB::raw('RAND()'));
This is a little bit weird usage, but works.
Edit: As #Alex said, this usage is cleaner and also works:
Posts::where_status(1)->order_by(DB::raw('RAND()'));
Use Laravel function
ModelName::inRandomOrder()->first();
You can easily Use this command:
// Question : name of Model
// take 10 rows from DB In shuffle records...
$questions = Question::orderByRaw('RAND()')->take(10)->get();
There is also whereRaw('RAND()') which does the same, you can then chain ->get() or ->first() or even go crazy and add ->paginate(int).
I prefer to specify first or fail:
$collection = YourModelName::inRandomOrder()
->firstOrFail();
Laravel has a built-in method to shuffle the order of the results.
Here is a quote from the documentation:
shuffle()
The shuffle method randomly shuffles the items in the collection:
$collection = collect([1, 2, 3, 4, 5]);
$shuffled = $collection->shuffle();
$shuffled->all();
// [3, 2, 5, 1, 4] - (generated randomly)
You can see the documentation here.
At your model add this:
public function scopeRandomize($query, $limit = 3, $exclude = [])
{
$query = $query->whereRaw('RAND()<(SELECT ((?/COUNT(*))*10) FROM `products`)', [$limit])->orderByRaw('RAND()')->limit($limit);
if (!empty($exclude)) {
$query = $query->whereNotIn('id', $exclude);
}
return $query;
}
then at route/controller
$data = YourModel::randomize(8)->get();
I have table with thousands of records, so I need something fast. This is my code for pseudo random row:
// count all rows with flag active = 1
$count = MyModel::where('active', '=', '1')->count();
// get random id
$random_id = rand(1, $count - 1);
// get first record after random id
$data = MyModel::where('active', '=', '1')->where('id', '>', $random_id)->take(1)->first();
Here's how I get random results in eloquent in one of my projects:
$products = Product::inRandomOrder()->limit(10);
10 - The number of random records to pull.
Try this code! It Works:
User::orderBy(DB::raw('RAND()'))->get();

Categories