In eloquent fetching data in fieldname=>fieldvalue keys - laravel-5

In laravel 5.8 making request
$searchResultsArray = SearchResult
::getBySourceId($next_sourceId['source_id'])
->select( 'field', 'value' )
->get()
->toArray();
I got resulting rows like :
$searchResultsArray::Array
(
[0] => Array
(
[field] => Id
[value] => 302530
)
[1] => Array
(
[field] => Domain
[value] => site.com
)
If there is a way to get
array of fieldname=>fieldvalue keys, like
Id => 302530
Domain=> site.com
without additive foreach block in my code?
If yes how?

Yes there is. Eloquent always returns collections. You could modify the collection first with mapWithKeys() (https://laravel.com/docs/5.8/collections#method-mapwithkeys) and then convert it to an array.
Try something like this:
$searchResultsArray = SearchResult
::getBySourceId($next_sourceId['source_id'])
->select( 'field', 'value' )
->get()
->mapWithKeys(function ($item) {
return [$item['field'] => $item['value']];
})
->all();

Related

Get current time in select in laravel

$product = Product::select('id', 'name', 'status',DB::raw('date(\'d-m-y\') as dateCurrent' ))
->whereDate('status', 3)
->get()
->toArray();
Result dateCurrent null :
Array
(
[0] => Array
(
[id] => 4
[name] => 'Iphone'
[dateCurrent] => null
)
[1] => Array
(
[id] => 5
[name] => 'samsung'
[dateCurrent] => null
)
)
I want to get current time right at select. Is there any way to get it? Thanks
date('d-m-y')
looks like php built function
if u want to db time
u can use NOW() function
and if u use db time
$product = Product::select('id', 'name', 'status', DB::raw('NOW() AS dateCurrent'))
->whereDate('status', 3)
->get()
->toArray();
but u want php server time
$product = Product::select(
'id', 'name',
'status', DB::raw(sprintf('%s AS dateCurrent', date('d-m-y'))))
->whereDate('status', 3)
->get()
->toArray();
https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_now

Getting all items in the collection mapWithKeys

I have:
$collection=Event::all();
$keyed = $collection->mapWithKeys(function ($item) {
return ['title' => $item['name'], 'start' => $item['event_date']];
});
$keyed->all() is returning only last item in the collection with changed keys:
Array
(
[title] => New Year
[start] => 2018-01-01
)
How do i get all events with changed keys?
The callback of mapWithKeys return an associative array conaining a single key / value pair, so if you just need name and event_date I suggest to use pluck like this:
$collection=Event::pluck('event_date', 'name');

Laravel Eloquent ORM relationship query

I need help, I have a problem with querying Model Relationships.
I actually know and get the job done using the query method but I'd like to know the "laravel way" of querying relationships.
Here's what's on my controller.
//HealthProfile Controller
//$id value is 2
$health_profiles = User::find($id)->with('health_profiles')->first();
problem is that the return for the query is the records for id = 1 and not id = 2. It basically ignored the "find" method. I just want to get the health profiles for a specific user_id.
[id] => 1
[firstname] => patrick
[lastname] => marino
[email] => patrick#gmail.com
[membership_code] => starpatrick
[birthdate] => 1989-05-17
[contact_number] => 1230123
[active] => 1
[created_at] => 2014-07-01 16:10:05
[updated_at] => 2014-07-01 16:10:05
[remember_token] =>
[health_profiles] => Array
(
[0] => Array
(
[id] => 1
[user_id] => 1
[parent_id] =>
[name] => patrick star
[relationship] =>
[gender] => male
[birthdate] => 1989-05-17
[marital_status] =>
[number_of_children] =>
[weigth] =>
[height] =>
[blood_type] =>
[blood_pressure] =>
[hdl] =>
[ldl] =>
[vldl] =>
[visual_activity] =>
[lifestyle] =>
[current_bmi] =>
[weight_goal] =>
[weekly_goal] =>
[rdc] =>
[created_at] => 2014-07-01 16:10:05
[updated_at] => 2014-07-01 16:10:05
)
This is my schema
//User model
public function health_profiles()
{
return $this->hasMany('HealthProfile');
}
//HealthProfile model
public function user()
{
return $this->belongsTo('User', 'user_id', 'id');
}
First a few words of explanation:
find($id) already runs the query (it uses where(id, $id)->first() under the hood) so place it at the end, because now you unwittingly did this:
User::find($id);
User::with('health_profiles')->first();
Another problem is, like you already noticed, that Eloquent won't work with this setup:
public function health_profiles() ...
$user = User::find($id);
$user->health_profiles; // null
because when loading dynamic properties (relations) it looks for camelCased method on the model.
However eager loading will work as expected:
$user = User::with('health_profiles')->find($id);
$user->health_profiles; // related model/collection
So you definitely should comply with the naming conventions if you want Eloquent to be your friend ;)
But that's not all. It will work the other way around:
public function healthProfiles() ...
$user = User::find($id);
$user->healthProfiles; // works, returns related model/collection
$user->health_profiles; // works as well, returns the model/collection
To sum up and answer your question, each of those will work for you:
// Assuming Profile is the model
// 2 queries
$user = User::find($id);
$profiles = $user->healthProfiles;
// or 1 query
$profiles = Profile::where('user_id', $id)->get();
// or 2 queries: 1 + 1 subquery
$profiles = Profile::whereHas('user', function ($q) use ($id) {
$q->where('users.id', $id);
})->get();
You can try putting the with before the find so that the builder knows to eager load that relationship on what you are trying to find.
$user = User::with('health_profiles')->find($user_id);
$health_profiles = $user->health_profiles;
Try this
User::with('health_profiles')->find($id);
I don't think you need to call the first method because find as it's stated will only find the one row of data that you need.
I've found the culprit. L4 has problems with snake cased methods! I changed it to camelCase and it worked.
$lawly = User::where('id', '=', 2)->first();
$lawly->healthProfiles->toArray()
src: https://coderwall.com/p/xjomzg

codeignite trying to get property of non-object not resolved

I am attempting to access the result set from a model query in the view. I have the following:
Controller:
$courseId = $this->session->userdata('courseId');
//echo "Course: ".$courseId;
if(isset($courseId) && $courseId != '')
{
$result = $this->Course_model->loadBasicDetailsEdit($courseId);
$data['basicCourseDetails'] = $result;
$this->load->view('course/basicDetails', $data);
}
Model:
function loadBasicDetailsEdit($courseId)
{
$this->db->select('*');
$this->db->where('course_id', $courseId);
$this->db->from('course');
$query = $this->db->get();
if ( $query->num_rows() > 0 )
{
return $query->result();
} else {
return FALSE;
}
}
and in the view I tried to print_r() and got this:
Array ( [0] => stdClass Object ( [course_id] => 8 [title] => Photography [summary] => [description] => [price] => [member_id] => 12 [category] => [audience] => [goals] => [date] => 2013-09-26 [production] => 0 ) )
I tried to access this using $basicCourseDetails->title or $basicCourseDetails['title']
but neither are working. Any hint as to why this is happening?
Regards,
try this:
foreach($basicCourseDetails as $basic){
echo($basic->title);
}
or something like this:
echo($basicCourseDetails[0]->title);
This is an array of objects
Array ( [0] => stdClass Object ( [course_id] => 8 [title] => Photography [summary] => [description] => [price] => [member_id] => 12 [category] => [audience] => [goals] => [date] => 2013-09-26 [production] => 0 ) )
Contains one stdObject in the array, so, first objects is 0, if there were more, then second item could have index 1 and so on. To retrieve data from the first (here is only one) stdobject you may use
echo $basicCourseDetails[0]->title; // title will be printed
You can send data to the view page by this line of code which is mentioned in above question.
$result = $this->Course_model->loadBasicDetailsEdit($courseId);
$data['basicCourseDetails'] = $result;
$this->load->view('course/basicDetails', $data);
But when you will access these data in view then you need to access all data one by one by using foreachloop in the view page.
For example if you have a view page like basic_details.php inside course folder then you need to write code like this to access these data.
foreach ($basicCourseDetails as $key => $value) {
$name = $value->name;
}
The above foreachloop can be written in view page where you want to access data.

Use Array Data in CodeIgniter Model as SQL?

In my controller, I am passing data to the model using the following code:
$data = array(
'gid' => $this->input->post('gid'),
'name' => $this->input->post('name'),
'pic' => $this->input->post('pic'),
'link' => $this->input->post('link')
);
var_dump($data);
$this->Login_model->insert_entry($data);
In my model, what I want to do is use the gid value as part of an SQL statement, like so:
$get_gid = $this->db->query('SELECT * FROM users WHERE gid = $gid');
Obviously this doesn't work, so I'm just wondering how I get the gid from $data and use it in my SQL statement?
Tested using
$get_gid = $this->db->where('gid', $data['gid'])->get('users');
print_r($get_gid);
However output is:
CI_DB_mysql_result Object ( [conn_id] => Resource id #30 [result_id]
=> Resource id #33 [result_array] => Array ( ) [result_object] => Array ( ) [custom_result_object] => Array ( ) [current_row] => 0
[num_rows] => 0 [row_data] => )
Did you try gid = $data['gid']
I assume that yours model method looks like this:
insert_entry($data)
{
here active record or query...
}
If yes try to display query to see if $data['gid'] is visible there
You can try it by
$this->db->get_compiled_select();
Or after query runs
$this->db->last_query();
Try this way:
$data = array(
'gid' => $this->input->post('gid'),
'name' => $this->input->post('name'),
'pic' => $this->input->post('pic'),
'link' => $this->input->post('link')
);
$gid = $data['gid'];
$this->db->where('gid',$gid);
$this->db->from('users');
$query = $this->db->get();
if($query)
{
//you can return query or you can do other operations here like insert the array data
//$this->db->insert('yourtable',$data);
return $query;
}
else
{
return FALSE;
}
You can try:
$get_gid = $this->db->query('SELECT * FROM users WHERE gid = '.$data['gid'].');
You just Forget after query $query->result().

Resources