Laravel - set array just with values - php

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);

Related

Laravel return relationship data based on locale

I have posts table that has related table where I store different translations based on post_id now when I want to return translation data based on user selected locale it says:
mb_strpos(): Argument #1 ($haystack) must be of type string, Closure given
Here is my function
$posts = Post::with('translations', function($q) {
$q->where('translate_code', app()->getLocale());
})->get();
dd($posts); // returning error above
But if I do this
$posts = Post::with('translations')->get();
dd($posts);
I will get following results
Here is translations data details:
My question is:
How can I return the one translation that has current locale name only?
If you using callback in with then use array of relations like below. Older version of laravel was working which you mentioned but latest version need array of relations when using callback.
$posts = Post::with(['translations'=> function($q) {
$q->where('translate_code', app()->getLocale());
}])->get();
using conditional eager loading should be like this:
$posts = Post::with(['translations'=> function($q) {
$q->where('translate_code', app()->getLocale());
}])->get();
while the relation name is the key, a closer to get data should be the value for the associative array for 'with' statement.
You can query your relation by using whereHas().
Docs: Laravel Docs Relationships
For example:
$posts = Post::whereHas('translations', function ($query) {
$query->where('translate_code', 'en');
})->get();
Maybe try to put the app()->getLocale() into a variable first. (after trying this out in tinker, this does seem te return a string, so may passing it by reference might help).

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();

Multiple Find Query in single database connection Laravel

Trying to enhance performance in Laravel query. Making multiple find operations on a single model, withing a loop, but trying to make it use a single database connection instance.
$departments = [];
foreach ($this->departments_only as $department) {
array_push($departments, Department::find($department));
}
return $departments;
No error. But just want a better performance.
As I can see the departments_only is array of ids, so you can use whereIn
$departments = Department::whereIn('id', $this->departments_only)->get();
This will return collection of departments.
For these cases, I use this library l5-repository
And do it:
$myArray = [1,2,3,4];
$result = $this->repository->scopeQuery(function ($query) use ($myArray) {
return $query
->whereIn("departament_id", $myArray);
})->all();
return $result
Or using raw queries and pure Laravel:
$myArray = [1,2,3,4,5];
$result = DB::table('departments')
->selectRaw('departament_id in (?)', $myArray)
->get();
if $this->departments_only has only ids in array then you can use
Model::whereIn('column','array')->get();
For more reference visit https://laravel.com/docs/5.8/queries#where-clauses
Or use DB object as,
DB::statement('SELECT * FROM table_name WHERE column_name IN ('"array_of_ids"')');

Laravel 5.2 - Change Data Format get from Eloquent

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.

Laravel modifying multiple rows at once

I have an array of $ids.
I'd like to essentially say:
foreach($ids as $id):
$user = User::find(1);
$user->life_expectancy -= 1;
$user->save();
endforeach;
Except I have thousands of ids in the array, and I'd much rather do something like:
$users = User::whereIn('id', $ids)->update(array('life_expectancy' => --1));
To just get it done in a single query. But that isn't going to work... is there another method?
I know I can update multiple users to all have the same life_expectancy, but I'd like it to be a modification of the previous value.
Check out this site, http://community.sitepoint.com/t/one-sql-statement-to-subtract-and-update-a-field-value/4673 if you decide to use a raw query, but looking on laravel's docs I think you can just do this,
$users = DB::table('users')
->whereIn('id', $ids)->decrement('life_expectancy');
App\User::whereIn('id',[1,2])->decrement('life_expectancy');
If you need -2 use next string:
App\User::whereIn('id',[1,2])->decrement('life_expectancy',2);

Categories