I have an array ($payments) returned by an Eloquent query with the following JSON encoded output:
[{"id":1, "user_id":"34","amount":"1000","status":"0","created_at":"2016-08-18 14:24:59","updated_at":"2016-08-18 14:24:59"},
{"id":3, "user_id":"33","amount":"300","status":"1","created_at":"2016-08-18 14:31:04","updated_at":"2016-08-18 14:33:20"},
{"id":4, "user_id":"33","amount":"1000","status":"0","created_at":"2016-08-18 14:31:27","updated_at":"2016-08-18 14:31:27"},
{"id":5, "user_id":"34","amount":"400","status":"1","created_at":"2016-08-18 14:42:02","updated_at":"2016-08-18 14:42:02"}]
I want to use the array_where() method in Laravel and filter $payments according this condition : status == 1, could anyone tell me how to do that?
If this is the result of an Eloquent query, it's not an array, it's a Collection. From the documentation:
All multi-result sets returned by Eloquent are an instance of the Illuminate\Database\Eloquent\Collection object
You can use the Collection's filter method, which takes a closure, and return the condition you want ('status' == 1) in the closure.
$filtered = $your_query_result->filter(function($value, $key) {
return $value->status == 1;
});
You may be surprised to find out that there is a php function called array_filter that does exactly that. Here it is in action
$array = [ ['id' => 1, 'status' => 0], ['id' => 2, 'status' => 1], ['id' => 3, 'status' => 0] ];
$array = array_filter($array, function ($item) {
return $item['status'] == 1;
});
Eloquents result cannot be json by default unless You call toJson() method.
Why not just add to Your database query condition?
Example:
$payments = Payment::where('status', '=', 1)->get(); // Payment is model
return response()->json($payments);
p.s. it's not recommended to get a big list of json data from db, parse it and filter it.
make better use of database and don't make Your life hard (:
Related
I'm filtering out non-unique arrays from my collection based only on a combination of if the "first_name" and "last_name" matches any others, but I want to drop a console.log for every match found. I've thought about using a foreach in a foreach to check element against one another, but that method seems far from elegant.
Is it possible to do this while using the Laravel Unique() method without using nested forEach's?
Example of what I'm currently doing:
$collection->unique(function ($item) {
return $item['first_name'].$item['last_name'];
})->each(function ($item, $key) use ($id) {
// Do stuff..
});
First store duplicates:
$collection = collect([1, 2, 3, 3, 4, 4, 4, 5]);
$duplicates = $collection->duplicates();
Then make your collection unique and store:
$collection = $collection->unique();
Output:
References:
https://laravel.com/docs/9.x/collections#method-duplicates
https://laravel.com/docs/9.x/collections#method-unique
I have column named flag and I want to update it if value is 1 to null and if value is null to 1 so far is easy to update this column but issue comes where I send multiple data to controller and not only one.
code
public function flagmultiplemessage(Request $request){
$ids = $request->input('ids');
DB::table('messages')->whereIn('id', $ids)
->whereNotNull('messages.flag')->update(['flag' => null])
->whereNull('messages.flag')->update(['flag' => '1']);
}
with function above i get:
message Call to a member function whereNull() on integer
dd
code above is something like this:
ids = [11, 12, 3]
database = [
11->flag = 1,
12->flag = null,
3->flag = 1,
]
the result of code above most change my database like:
database = [
11->flag = null,
12->flag = 1,
3->flag = null,
]
any idea why i get error?
it occurred because you called whereNull method on update method.
You should run 3 separate query like this.
public function flagmultiplemessage(Request $request){
$ids = $request->input('ids');
DB::transaction(function () use ($ids) {
DB::table('messages')->whereIn('id', $ids)
->whereNotNull('messages.flag')->update(['flag' => 0]);
DB::table('messages')->whereIn('id', $ids)
->whereNull('messages.flag')->update(['flag' => 1]);
DB::table('messages')->whereIn('id', $ids)
->where('messages.flag', 0)->update(['flag' => null]);
});
}
but for better performance I suggest you use boolean for flag column and use this simple query
DB::table('messages')->whereIn('id', $ids)->update(['flag' => DB::raw('!flag')]);
The main reason for the error is that the update() method is not chainable
Alternatively, You can do the update in one query by using the mysql Case statement.
public function flagmultiplemessage(Request $request) {
$ids = $request->input('ids');
DB::table('messages')->whereIn('id', $ids)
->update(['flag' => DB::raw('case when flag is null then 1 else null end') ]);
}
You can do this
DB::table('messages')->whereIn('id', $ids)->where(function ($query) {
$query->whereNotNull('messages.flag')->update(['flag' => null])
->orWhereNull('messages.flag')->update(['flag' => '1']);
})
I have a collection like that, when i perform groupBy('name'), it return like this one
my question is how to merge the "id_area" key when i perform groupBy('name') ?
the expected result is more like this
"name" => "A"
"id_area" => [3, 1]
my eloquent code is
$x = Kegiatan::orderBy('name')->groupBy('name')->get();
$y = $x->map(function ($group) {
return ["name" => $group->name, "id_area" => $group->id_area];
});
dd($y);
Don't use groupBy() method of your query builder instead just get your data and then use groupBy() method of Illuminate\Support\Collection class
$collection = Kegiatan::orderBy('name')->get();
$grouped = $collection->groupBy('name');
$grouped->toArray();
Using groupBy() on query builder will group records by database query and using collection's groupBy() will group records once data is fetched by query
can i retrieve single row from database like this in Laravel
["name"=>"jhon",
"age"=>"18"
]
Use the first() method:
User::where('name', 'John Smith')->first();
Or the find() method:
User::find($id);
It will return an object. If you need an array, use the toArray() method to convert an object to an array:
User::find($id)->toArray();
You can also use Eloquent Collection methods to transform it however you want.
$people = User::where('name', 'John Smith')->get()->map(function ($person) {
return [
'id' => $person->id,
'name' => $person->name
];
});
Use first() method along with id because id is unique key for every row
User::whereId($id)->first();
I have a model like this-
$feature_project = FeatureProject::select('feature_id')
->where('project_id', $project->id)
->get();
And if I return it, I am getting a output like this-
[
{
"feature_id": 2
},
{
"feature_id": 4
},
{
"feature_id": 9
}
]
But I want t output like this-
[2,4,9]
So I need to convert the output.
But I am not finding a way without using for-each loop (make a temp array, push all elements to that array from current array with a for-each loop).
But I think there is more smart way than that in Laravel to do that.
I think Laravel Collection is used for this purpose.
You can call pluck() method on the query builder.
$feature_project = FeatureProject::select('feature_id')
->where('project_id', $project->id)
->pluck('feature_id'); // [2,4,9]
https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Builder.html#method_lists
Alternatively, you can use PHP's array_column() function for raw arrays.
http://php.net/manual/en/function.array-column.php
In Laravel's collections, you can call a method called Flatten, which flattens a multi-dimensional collection into a single dimension.
https://laravel.com/docs/5.2/collections#method-flatten
$collection = collect(['name' => 'taylor', 'languages' => ['php', 'javascript']]);
$flattened = $collection->flatten();
$flattened->all();
// ['taylor', 'php', 'javascript'];
With a fairly flat object, it should return just the values.
Use pluck():
$feature_project = FeatureProject::where('project_id', $project->id)->pluck('feature_id');
An alternative way also will be helpful in some cases.
We can run raw queries inside select function.
Here is an example:
$feature_project = FeatureProject::select(DB::raw('GROUP_CONCAT("feature_id")))
->where('project_id', $project->id)
->get();
In DB::raw we can run mysql query with function and case same as mysql query.
You can use lists() and toArray() :
$feature_project=FeatureProject::where('project_id', $project->id)->lists('id')->toArray();
Hope this helps.