Laravel 5.2 - Change Data Format get from Eloquent - php

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.

Related

WhereIn Inside ->where() array - Laravel Query Builder

I'm trying use a whereIn inside a where array I am passing to Laravel query Builder:
$where = [['Participants.Client_Id','IN', $clientId]];
DB::table('Participants')->where($where)->get()
Something like is what I want to achieve, and I know there are works around such as using whereIn, but I'm sharing here a small piece of code to give you an idea, so I need to change the array to make it works as a whereIn, not changing the ->where to ->whereIn or ->whereRaw
DB::table('participants)->whereIn('Participants.Client_Id',$clientId)->get();
You must collect the IDs in the $clientId variables.
If I understand, you could do something like that :
$wheres = [['Participants.Client_Id','IN', [$clientId]]];
$query = DB::table('Participants');
foreach($wheres as $where) {
$query->where($where[0], $where[1], $where[2]);
}
$participants = $query->get();
As laravel document , you can use array in where and each element of this array must be a array with three value . So your $where variable is correct.
But as I searched in operator is not supported by query builder of where.

My whereJsonContains not working (Laravel 5.8)

I have problem with my laravel query.
Now I use query like this:
$courses = Course::whereJsonContains('schedule->day', 1)->get();
It doesn't work.
I'm using postgreSql 9.6 and my database and raw query look like this
http://sqlfiddle.com/#!17/88fd2/1/0
I want to select class where have schedule in day = 1
If you define the column as schedule->day, MySQL assumes that this is an array of integers. In your case it's an array of objects, so you have to target the parent array and add the property name you are looking for in the second argument.
Like so:
$courses = Course::whereJsonContains('schedule', ['day' => 1])->get();
I solved with
$courses = Course::whereJsonContains('schedule', [['day' => '1']])->get();
I solved with
$products=ProductShop::active()
->whereJsonContains('tag', [['value' => "tampa"]])->get();
If you're querying the value уоu don't need to use whereJsonContains, simply use a regular where query such as:
$courses = Course::where('schedule->day', 1)->get();`
If you want to check if day exists in Json, use whereJsonLength such as:
$courses = Course::whereJsonLength('schedule->day', '>', 0)->get();

Laravel - set array just with values

I'm trying to send an email to multiple emails, so I did a query to my users tables but the result is an array with keys that don't work mail->to().
I need an array like this: $owners = ['myoneemail#esomething.com', 'myother#esomething.com','myother2#esomething.com']; from database.
My query:
$owners = DB::table('users')->select('email')->where('active', 1)->where('userType', 1)->get();
I also try use ->toArray() but comes with keys.
Email:
Mail::send('email-view', $data, function($message) use ($data, $owners)
{
$message->from('no-reply#email.pt' , 'FROM');
$message->to($owners)->subject('subject');
});
$owners = DB::table('users')->where('active', 1)->where('userType', 1)->pluck('email')->toArray();
You can use ->pluck(), like this:
$owners = DB::table('users')->select('email')->where('active', 1)->where('userType', 1)->get();
$emailList = $owners->pluck('email');
$owners = DB::table('users')->where('active', 1)->where('userType', 1)->pluck('email');
or
$owners = User::where('active', 1)->where('userType', 1)->pluck('email');
here User is your model name
First of all, the where condition is not proper in your query builder code.
It has to be like:
$query->where([
['column_1', '=', 'value_1'],
['column_2', '<>', 'value_2'],
[COLUMN, OPERATOR, VALUE],
...
])
You can use pluck() to get the list in Laravel 5.
All collections also serve as iterators, allowing you to loop over them as if they were simple PHP arrays:
foreach ($owners as $owner) {
echo $owner->filed_name;
echo $owner->filed_name;
...
}
There is no restriction for using the core PHP code while using a PHP framework. You may refer the official PHP Arrays Manual page to work with the language construct.
If you need to convert JSON to array, use:
json_decode($owners);

Laravel 5.2 - pluck() method returns array

I'm trying to upgrade my project L5.1 -> L5.2. In upgrade guide there's one thing which isn't clear for me:
The lists method on the Collection, query builder and Eloquent query
builder objects has been renamed to pluck. The method signature
remains the same.
That's ok, rename refactoting from lists() to pluck() isn't a problem. But what with useful pluck() method which was in L5.0 and L5.1?
From the 5.0 documentation:
Retrieving A Single Column From A Row
$name = DB::table('users')->where('name', 'John')->pluck('name');
What is the alternative for old pluck() method in L5.2?
UPDATE:
Example:
var_dump(DB::table('users')->where('id', 1)->pluck('id'));
L5.1:
// int(1)
L5.2:
// array(1) { [0]=> int(1) }
The current alternative for pluck() is value().
In Laravel 5.1+, you can use the value() instead of pluck.
To get first occurence, You can either use
DB::table('users')->value('name');
or use,
DB::table('users')->where('id', 1)->pluck('name')->first();
laravel pluck returns an array
if your query is:
$name = DB::table('users')->where('name', 'John')->pluck('name');
then the array is like this (key is the index of the item. auto incremented value):
[
1 => "name1",
2 => "name2",
.
.
.
100 => "name100"
]
but if you do like this:
$name = DB::table('users')->where('name', 'John')->pluck('name','id');
then the key is actual index in the database.
key||value
[
1 => "name1",
2 => "name2",
.
.
.
100 => "name100"
]
you can set any value as key.
I use laravel 7.x and I used this as a workaround:->get()->pluck('id')->toArray();
it gives back an array of ids [50,2,3] and this is the whole query I used:
$article_tags = DB::table('tags')
->join('taggables', function ($join) use ($id) {
$join->on('tags.id', '=', 'taggables.tag_id');
$join->where([
['taggable_id', '=', $id],
['taggable_type','=','article']
]);
})->select('tags.id')->get()->pluck('id')->toArray();
In the original example, why not use the select() method in your database query?
$name = DB::table('users')->where('name', 'John')->select("id");
This will be faster than using a PHP framework, for it'll utilize the SQL query to do the row selection for you. For ordinary collections, I don't believe this applies, but since you're using a database...
Larvel 5.3: Specifying a Select Clause

Filter an object in Laravel 4.1

I am very new to Laravel and php and i am facing an issue with a collection. The collection is generated in this way:
$users = $media->campaign->users;
Which return this data:
[{id: 1, name: "name", suspended: 0},{id: 2, name: "name2", suspended: 1}]
How can i filter this object in laravel 4.1 to get only the elements that have 0 as suspended?
Use array_filter(array $array[, callable $callback[, int $flag]]):
array_filter($users, function($value) {
return($value->suspended === 0);
});
Check more in Laravel 4.2 documentation, Taylor wrote there that filtering collections use array_filter function. Also you should can use $users = $users->filter(function($user) {}); method.
Also, thanks to #xAoc, you can use filtering on SQL query:
$users = $media->campaign
->users()
->where("suspended", "=", 0)
->get();
Since you're doing a direct "equals" comparison, Laravel's Collection has a where() method you can use. For example:
$users = $media->campaign->users;
$users->where('suspended', 0);
This is a good option if you already have the Collection. If, however, you have control over generating the Collection, it would be more beneficial to only get the actual data you're looking for. In this case, you can add the where clause to the SQL statement, so you will only retrieve the final records you want. For example:
$users = $media->campaign->users()->where('suspended', '=', 0);
NB: the where() method on the Collection and the where() method on the query builder have different signatures. The query builder lets you pass in an operator to use ('=', '>', '<', etc). The Collection only does a direct equals comparison. This trips up a lot of people.

Categories