Any way to except empty field from $request->all() in laravel? - laravel-5.6

I want to except empty value field from $request->all();
Array ( [first_name] => Dev 1 [password] => [last_name] => [phone] => 123456 [password_confirmation] => )
I got the array like this but I want to except field from above array like last_name, password which has no value.
Any way to do this without for loop.
I mean laravel provide any default method for that ?
Thanks

array_filter will remove empty elements:
$filtered = array_filter($request->all());

Related

Inserting multipe rows from dynamic form fields using laravel 5

How can I store multiple form array data in laravel, as I need to create a new record against each array index.
[0] => Array
(
[make] => test
[model] => XYZ
)
[1] => Array
(
[make] => s4
[model] => BB
)
[2] => Array
(
[make] => 99
[model] => AX
)
This is what I am trying to, but here loop get executed 6 times instead of three
$results = $request->all();
foreach ($results as $key => $value) {
echo $key;
// insert operation
}
I believe you should specify the control/field because the Request contains other (non-data) information. Something like:
$results = $request['array_name'];
https://laravel.com/docs/5.4/queries#inserts
Model::insert($request->all())
This will mass insert each array into your database. insert do not automatically set datetime values for created_at and updated_at, note that the array keys should match your table columns, and make sure your model has these fields as $fillables.

laravel 5.4 validation array with keys

In laravel 5.4 when validation is failed I do like:
if ($validator->fails()) {
$errors_list = $validator->messages()->all();
and I got array like :
[errors_list] => Array
(
[0] => The image has already been taken.
[1] => The is main has already been taken.
)
What I dislike in this output that actuall name of error field is ommitted.
Code
echo '<pre>$validator->messages()::'.print_r($validator->messages(),true).'</pre>';
has output:
$validator->messages()::Illuminate\Support\MessageBag Object
(
[messages:protected] => Array
(
[image] => Array
(
[0] => The image has already been taken.
)
[is_main] => Array
(
[0] => The is main has already been taken.
)
)
[format:protected] => :message
)
And I did not find how access to messages data.
I would like to get array like:
[errors_list] => Array
(
[image] => The image has already been taken.
[is_main] => The is main has already been taken.
)
Is there is a way to make it ?
Thanks!
I hope this will work for you.
$errors->has('image');
$errors->get(image);
$errors->has('is_main');
$errors->get(is_main);
It's a tricky one. The reason it's like that is because there may be multiple validation errors happening at once. However if you only have a single rule per entry:
array_combine($validator->messages()->keys(),$validator->messages()->all())

How to get distinct values for non-key column fields in Laravel?

This might be quite easy but have no idea how to.
I have a table that can have repeated values for a particular non-key column field. How do I write a SQL query using Query Builder or Eloquent that will fetch rows with distinct values for that column?
Note that I am not fetching that column only, it is in conjunction with other column values, so distinct() might not really work. So that question basically can be how to specify the column that I want to be distinct in a query now that distinct() accepts no parameters?
You should use groupby. In Query Builder you can do it this way:
$users = DB::table('users')
->select('id','name', 'email')
->groupBy('name')
->get();
In Eloquent you can also query like this:
$users = User::select('name')->distinct()->get();
in eloquent you can use this
$users = User::select('name')->groupBy('name')->get()->toArray() ;
groupBy is actually fetching the distinct values, in fact the groupBy will categorize the same values, so that we can use aggregate functions on them. but in this scenario we have no aggregate functions, we are just selecting the value which will cause the result to have distinct values
Though I am late to answer this, a better approach to get distinct records using Eloquent would be
$user_names = User::distinct()->get(['name']);
**
Tested for Laravel 5.8
**
Since you wanna get all columns from the table, you can collect all of the data and then filter it using Collections function called Unique
// Get all users with unique name
User::all()->unique('name')
or
// Get all & latest users with unique name
User::latest()->get()->unique('name')
For more information you can check Laravel Collection Documentations
EDIT: You might have issue with perfomance, by using Unique() you'll get all data first from User table, and then Laravel will filter it.
This way isn't good if you have lots of Users data. You can use query builder and call each fields that you wanna use, example:
User::select('username','email','name')->distinct('name')->get();
Grouping by will not work if the database rules don't allow any of the select fields to be outside of an aggregate function. Instead use the laravel collections.
$users = DB::table('users')
->select('id','name', 'email')
->get();
foreach($users->unique('name') as $user){
//....
}
Someone pointed out that this may not be great on performance for large collections. I would recommend adding a key to the collection. The method to use is called keyBy. This is the simple method.
$users = DB::table('users')
->select('id','name', 'email')
->get()
->keyBy('name');
The keyBy also allows you to add a call back function for more complex things...
$users = DB::table('users')
->select('id','name', 'email')
->get()
->keyBy(function($user){
return $user->name . '-' . $user->id;
});
If you have to iterate over large collections, adding a key to it solve the performance issue.
Note that groupBy as used above won't work for postgres.
Using distinct is probably a better option - e.g.
$users = User::query()->distinct()->get();
If you use query you can select all the columns as requested.
$users = User::select('column1', 'column2', 'column3')->distinct()->get(); retrieves all three coulmns for distinct rows in the table. You can add as many columns as you wish.
I found this method working quite well (for me) to produce a flat array of unique values:
$uniqueNames = User::select('name')->distinct()->pluck('name')->toArray();
If you ran ->toSql() on this query builder, you will see it generates a query like this:
select distinct `name` from `users`
The ->pluck() is handled by illuminate\collection lib (not via sql query).
// Get unique value for table 'add_new_videos' column name 'project_id'
$project_id = DB::table('add_new_videos')->distinct()->get(['project_id']);
I had the same issues when trying to populate a list of all the unique threads a user had with other users. This did the trick for me
Message::where('from_user', $user->id)
->select(['from_user', 'to_user'])
->selectRaw('MAX(created_at) AS last_date')
->groupBy(['from_user', 'to_user'])
->orderBy('last_date', 'DESC')
->get()
Here are 3 ways I have tested that will give same result:
User::distinct()->get(['name'])->pluck('name');
User::select('name')->distinct()->pluck('name')->all();
DB::table('users')->select('name')->groupBy('name')->get()->pluck('name')->all();
For those who like me doing same mistake. Here is the elaborated answer
Tested in Laravel 5.7
A. Records in DB
UserFile::orderBy('created_at','desc')->get()->toArray();
Array
(
[0] => Array
(
[id] => 2073
[type] => 'DL'
[url] => 'https://i.picsum.photos/12/884/200/300.jpg'
[created_at] => 2020-08-05 17:16:48
[updated_at] => 2020-08-06 18:08:38
)
[1] => Array
(
[id] => 2074
[type] => 'PROFILE'
[url] => 'https://i.picsum.photos/13/884/200/300.jpg'
[created_at] => 2020-08-05 17:20:06
[updated_at] => 2020-08-06 18:08:38
)
[2] => Array
(
[id] => 2076
[type] => 'PROFILE'
[url] => 'https://i.picsum.photos/13/884/200/300.jpg'
[created_at] => 2020-08-05 17:22:01
[updated_at] => 2020-08-06 18:08:38
)
[3] => Array
(
[id] => 2086
[type] => 'PROFILE'
[url] => 'https://i.picsum.photos/13/884/200/300.jpg'
[created_at] => 2020-08-05 19:22:41
[updated_at] => 2020-08-06 18:08:38
)
)
B. Desired Grouped result
UserFile::select('type','url','updated_at)->distinct('type')->get()->toArray();
Array
(
[0] => Array
(
[type] => 'DL'
[url] => 'https://i.picsum.photos/12/884/200/300.jpg'
[updated_at] => 2020-08-06 18:08:38
)
[1] => Array
(
[type] => 'PROFILE'
[url] => 'https://i.picsum.photos/13/884/200/300.jpg'
[updated_at] => 2020-08-06 18:08:38
)
)
So Pass only those columns in "select()", values of which are same.
For example: 'type','url'. You can add more columns provided they have same value like 'updated_at'.
If you try to pass "created_at" or "id" in "select()", then you will get the records same as A.
Because they are different for each row in DB.
In my case (with Laravel 9), I need:-
to use where clause.
to get complete row.
to get unique entries for specific column.
As more complex query, but still, I have an easy approach. May be that help you also.
User::where('id',auth()->user()->id)->distinct('name')->get();

getting the value of array key in codeigniter

I have the following line in my controller:
$data['faq'] = $this->faqModel->get();
This data print the following using the print_r
Array
(
[faq] => Array
(
[0] => Array
(
[faqid] => 12
[catid] => 122
[question] => How this CMS works
[question_en] => How this CMS works
[answer] => How this CMS works?
[answer_en] => How this CMS works?
[sorder] => 2
[visible] => 1
)
[1] => Array
(
[faqid] => 8
[catid] => 121
[question] => How does the design cost?
[question_en] => How does the design cost?
[answer] => How does the design cost?
[answer_en] => How does the design cost?
[sorder] => 1
[visible] => 1
)
)
)
I want to use the value stored in the [catid] key, and I am trying to do something like:
$data['faq']['catid'] to get that value in the controller (I want to make another select with that value) But I am getting with this error message: Undefined index: catid
Anyone can help me to get the value of ['catid']???
Regards, Zoran
Its 3 dimensional array u look closely there is two elements in faq array. You must wrote something like this: $data['faq'][0]['catid'] or $data['faq'][1]['catid']
The way you are accessing the array is incorrect, you are missing the item index on the second level. The correct way to use it as you are doing would be to do
echo $data['faq'][0]['faqid']; //faqid of the first item
However, this will only show one faqid at a time, and it not so useful when you are iterating. So, a good way would be this way.
foreach($data['faq'] as $value) {
echo $value['faqid'];
}

CodeIgniter: Using array within array

I am following nettut+ tutorial for pagination and to store POST inputs as querystrings in db. So far, everything works fine until, suppose if I get an array as POST input, i am unable to loop through it and get all the array values and to store into query_array (i.e., store array within array).
The snippets below:
$query_array = array(
'gender' => $this->input->post('gender'),
'minage' => $this->input->post('minage'),
'maxage' => $this->input->post('maxage'),
'Citizenship' => $this->input->post('citizenship'), // checkboxes with name citizenship[]
);
This returns only last stored array value in Citizenship.
The output array:
Array ( [gender] => 1 [minage] => 18 [maxage] => 24 [Citizenship] => 2 )
makes the query string as:
&gender=1&minage=18&maxage=24&Citizenship=2
But, my requirement is to get all the values of 'Citizenship' array instead of last stored value.
The output required to make query string:
Array ( [gender] => 1 [minage] => 18 [maxage] => 24 [Citizenship] => 2 [Citizenship] => 4 [Citizenship] => 6 )
The query string :
&gender=1&minage=18&maxage=24&Citizenship[]=2&Citizenship[]=4&Citizenship[]=6
Any help appreciated..
Thanks.
Doesn't look like code ignighter supports un-named multidimensional arrays as input without a bit of hacking.
If you can access raw $_POST data try replacing
$this->input->post('citizenship')
with
array_map('intval',$_POST['citizenship'])
Alternativly add keys to your post data:
&gender=1&minage=18&maxage=24&Citizenship[0]=2&Citizenship[1]=4&Citizenship[2]=6
I fixed it myself. I just looped through the POST array and got the individual array key & pair values.
foreach($_POST['Citizenship'] as $k => $v) {
$Citizenship[$v] = $v;
}
Hope this helps someone who face similar problem.

Resources