Laravel Eloquent: getDictionary with object value as value of result - laravel

Currently, $mymodel->getDictionary(); returns:
What I am looking for is this:
"7gct5YaTvuxBmY2" => "Leadership",
"7NrXZepqczMSHqM" => "...",
"..." => "...",
...
The only way I have managed to do this is:
$construct_obj = OrganizationalConstruct::where('is_root', 0)->where('organization_id', $this->current_company->company_id)->get();
$constructs = [];
$constructs[''] = '';
for ($i = 0; $i < count($construct_obj); $i++) {
$constructs[$construct_obj[$i]->organizational_construct_id] = $construct_obj[$i]->construct_name;
}
Is there an easier way of getting the format "key" => "speific-column-value" ?
I have tried:
keyBy
lists
getDictionary
map

You should call pluck directly on the query, so that you don't pull down all attributes for all models:
$dictionary = OrganizationalConstruct::where('is_root', 0)
->where('organization_id', $this->current_company->company_id)
->pluck('construct_name', 'organizational_construct_id');
Note: lists is deprecated, and will be removed in Laravel 5.3. Use the pluck method instead.

Quite a simple answer actually. It looks like the lists methods can accept more than 1 argument, allowing me to pass through the id as parameter 1 and name as parameter 2 giving me the required result of key => value in one line.
So this:
$construct_obj = OrganizationalConstruct::where('is_root', 0)->where('organization_id', $this->current_company->company_id)->get();
$constructs = [];
$constructs[''] = '';
for ($i = 0; $i < count($construct_obj); $i++) {
$constructs[$construct_obj[$i]->organizational_construct_id] = $construct_obj[$i]->construct_name;
}
becomes this:
$construct_obj = OrganizationalConstruct::where('is_root', 0)->where('organization_id', $this->current_company->company_id)->get();
$construct_obj->lists('construct_name', 'organizational_construct_id');
Hope this helps someone else.

Related

see value according to the array

I do a select and get several results in array but I need to get the correct value for each step and set up a condition.
$step = DB::table('records')->where('id_user',$userId)->get();
for($i = 0; $i < count($step); $i++)
{
echo $step[$i]->id_step;
}
Id_step returns me values for each step where on the blade I need to get and see if id_step = 1 is true id_step = 2 is true.
This for is returning me only one value and it has 3 records in the table.
First of all. After a select you get an instance of Eloquent\Collection
Not an array.
So that said to loop do this:
$steps = DB::table('records')->where('id_user',$userId)->get();
foreach($steps as $row) {
echo $row;
}
Since you are familiar with arrays do this:
$steps->toArray();
Now your result is an array
Working insert in view this code.
#for($i = 0; $i < count($step); $i++)
#if($step[$i]->id_step == 2)
working
#else
not working
#endif
#endfor

generate more than one random code in laravel and save it to database

I'm a newbie in laravel. I have to generate multiple random characters at once in my laravel project and then save them to database. Any example or advise that quite easy to understand? thank you
A for loop may be appropriate for you in this case. If you don't have an object for the codes, you can do something like this:
$total_wanted = 100;
for ( $i = 0; $i < $total_wanted; $i++ ) {
DB::table('codes')->insert(['code' => uniqid("prefix")]);
}
If you do have a Code object, you can do it like this instead:
$total_wanted = 100;
for ( $i = 0; $i < $total_wanted; $i++ ) {
$code = new Code;
$code->code = uniqid("prefix");
$code->save();
}
echo uniqid('code_', true);
You generate a random, unique string based on current timestamp, so it can not be a duplicate.
Then simple store it in the database as a varchar
More about this function here

how to increment day by one to find the next desired day in laravel

I've an array of day name like ['Wednesday','Sunday','Monday']
now I want to find the next available dates That matched with the array from today's date. I want date. I tried for so long but none of them were successful. My code is given below
$datesAvailable = array();
$count = 0;
$dateToday = Carbon::now()->toDateTimeString();
//$avlDays is the array of day names
$avlDays = DB::table('doctor_schedules')
->select('available_days')
->where('department',$receivedDepartment)
->Where('doctor_id', $receivedDoctor)
->get();
for($k=5; $k > 0; $k++)
{
$dateToday = $dateToday->endOfWeek();
// $parsedDate = Carbon::parse($dateToday);
$dateTodayFormated = new Carbon($dateToday);
$nextDayName = $dateTodayFormated->englishDayOfWeek;
for($i = 0; $i <= 2; $i++)
{
if($avlDays === $nextDayName)
{
$datesAvailable[$count] = $nextDayName;
$count++;
}
}
}
return (['availableDates' => $dateToday]);
Solved
For the current date use
now()
https://laravel.com/docs/6.x/helpers#method-now
Carbon does this.
foreach ($avlDays as $day) {
$nextDay = Carbon::parse("next $day");
// do something with $nextDay...
}
So, assuming $avlDays is returning you a Carbon date range:
$avlDays = DB::table('doctor_schedules')
->select('available_days')
->where('department',$receivedDepartment)
->Where('doctor_id', $receivedDoctor)
->get()
->toArray();
The code below assumes that the array value from ['monday', 'tuesday' ...] is saved as $weekday.
If you are trying to find a specific date within a range that falls on a certain weekday, you can do something like:
$availableAppointments = [];
foreach ($avlDays as $day) {
if ($day->isDayOfWeek($weekday)) {
$availableAppointments[] = $day;
}
Then you can use $availableAppointments to list out the available dates on that day of the week.

Count number of same values in JSON array and convert it to string

My JSON looks something like this:
[
{"pet_type":"Dog","weight":"26","description":"Akita"},
{"pet_type":"Dog","weight":"6","description":"Pug"},
{"pet_type":"Cat","weight":"4","description":"Manx"},
{"pet_type":"Dog","weight":"12","description":"Beagle"},
{"pet_type":"Cat","weight":"5","description":"Siberian"}
]
How could I convert it to a string which would look like3 Dogs, 2 Cats?
The way I tried is filling an array with pet_type and than use array_count_values to count number of same records, and later I go through that array in a foreach and concat string like this:
foreach ($count_animals as $type => $number) {
$animals .= $number.' '.str_plural($type, $number).', ';
}
This works, but my question is, could I do it with less code, directly from JSON, without using one more foreach loop?
If it works, you can keep your code.
If you want less code, you can use this version :
$json = '[
{"pet_type":"Dog","weight":"26","description":"Akita"},
{"pet_type":"Dog","weight":"6","description":"Pug"},
{"pet_type":"Cat","weight":"4","description":"Manx"},
{"pet_type":"Dog","weight":"12","description":"Beagle"},
{"pet_type":"Cat","weight":"5","description":"Siberian"}
]';
print_r(array_count_values(array_map(function($item) {
return $item['pet_type'];
}, json_decode($json, true))));
Gonna display :
Array ( [Dog] => 3 [Cat] => 2 )
in your controller
$pet = Pet::get();
$petcount = Pet::where('pet_type','Dog')->get();
In your blade
<h1>{{count($petcount)}} Dog</h1>

Cakephp 3 How to make session array

I am trying to write session in controller. My structure is
$_SESSION['a'][0] = 1;
$_SESSION['a'][1] = 2;
$_SESSION['a'][2] = 3;
And I am trying this
Configure::write('Session', ['a' =>'1'])
But it is not working. How do this in cakephp 3 way
To write variable in Session in CakePHP 3 you need to write following code :
$this->request->session()->write('Your Key',Your_array);
To know more information you can visit here :
http://book.cakephp.org/3.0/en/development/sessions.html
To make things perfectly clear:
// code writing array to session
$a = [ "abc" => "word", "123" => 42, "?" => $b ];
$a["more"] = "if you need to add";
$a[] = "whatever";
$this->request->session()->write( 'my_array', $a );
// code reading array from session
$recall = $this->request->session()->read( 'my_array' );
debug( sprintf( "What's the word? [%s]", $recall["abc"] ) );
You can simply use
$session->write([
'key1' => 'blue',
'key2' => 'green',
]);
I am refering to
http://book.cakephp.org/3.0/en/development/sessions.html#reading-writing-session-data
The answer is that this cannot be done in CakePHP 3.x
In vanilla PHP, it's possible to do this:
<?php
session_start();
$_SESSION['a'][0] = 1;
$_SESSION['a'][1] = 2;
$_SESSION['a'][2] = 3;
var_dump($_SESSION);
?>
Which will output:
array(1) {
["a"]=> array(3) {
[0]=> int(1)
[1]=> int(2)
[2]=> int(3)
}
}
This is correct, and what should happen.
In CakePHP, you cannot specify arrays in the session key. For example:
$this->request->session()->write('a[]', 1);
$this->request->session()->write('a[]', 2);
$this->request->session()->write('a[]', 3);
Will not work.
If you remove the [] the value will get overwritten. For example:
$this->request->session()->write('a', 1);
$this->request->session()->write('a', 2);
$this->request->session()->write('a', 3);
The value of $this->request->session()->read('a') would be 3. The values 1 and 2 have been overwritten. Again, this is to be expected because you're overwriting the key a each time. The equivalent vanilla PHP for this is:
$_SESSION['a'] = 1;
$_SESSION['a'] = 2;
$_SESSION['a'] = 3;
Due to the lack of an indexed array, $_SESSION['a'] gets overwritten each time. This is normal behaviour. It needs to have the indexes (e.g. ['a'][0], ['a'][1], ...) to work!
The other answers where they have given things like key1 and key2 are not appropriate. Because there are many situations where you want everything contained within an indexed array. Generating separate key names is wrong for this type of scenario.
My edit of the accepted answer was rejected, so I present the - seemingly necessary - explicit code example, for the benefit of #Andy and others.
// code to write to session
$a = [ 0 => "zero", 1 => "one", 2 => "two" ];
$a[] = "three";
$this->request->session()->write( 'my_array', $a );
// code to read from session
$z = $this->request->session()->read( 'my_array' );
debug( $a[3] ); // outputs "three"

Resources