Codeigniter best approach to load data from model - codeigniter

Im trying to load data from a model if the data from a previously loaded model request is_numeric. I have written my code like this, though it doesn't work and i sort of get why. But i dont know how to get the content from the data['schedule_item'].
$this->load->model('schedule_model');
$this->load->model('partners_model');
$data['schedule_item'] = $this->schedule_model->getAll();
if(is_numeric($schedule_item['featured_partner1']) {
$data['featured_partner1'] = $this->schedule_model->get_partner($schedule_item['featured_partner1']);
}

You are getting the wrong variable you have assigned the model values on the index of $data array not to $schedule_item so it is undefined $schedule_item will be accessible in view only when all the indexes of $data is converted to the variables you should try to do this like
$this->load->model('schedule_model');
$this->load->model('partners_model');
$schedule_item=$this->schedule_model->getAll();
$data['schedule_item'] =$schedule_item;
if(is_numeric($schedule_item['featured_partner1']) {
$data['featured_partner1'] = $this->schedule_model->get_partner($schedule_item['featured_partner1']);
}
OR
$this->load->model('schedule_model');
$this->load->model('partners_model');
$data['schedule_item'] =$this->schedule_model->getAll();
if(is_numeric( $data['schedule_item']['featured_partner1']) {
$data['featured_partner1'] = $this->schedule_model->get_partner($schedule_item['featured_partner1']);
}

Related

Laravel filtered collection is no longer filtered after json encoding

I have an Eloquent collection with an eager loaded relationship. When I filter this eager loaded relationship, it works fine, but if I encode it as JSON (to pass it to my front end Javascript framework), the collection is no longer filtered.
Simplified example:
$questions = Question::with('variables')->get();
foreach($questions as $key => $q) {
$questions[$key]->variables = $q->variables->reject(function($v) {
return $v->type == 3;
});
}
dd($questions);
If I look at the $questions variable at this point, my collection is correctly filtered. If, however, I add json_decode(json_encode($questions)) following line before dumping, the collection is no longer filtered.
Note that in my real application, I have to do some things with the rejected variables before throwing them out of the collection, so I cannot simply filter them out during the query.
My workaround right now is to json encode and decode the collection, then do an array filter to get rid of the variables I do not want to pass to the front end. This works, but seems like a terribly inelegant and unnecessary solution. Am I doing something wrong or is this the expected behavior?
I'm still running Laravel 5.8 on this application in the event that this behavior has changed on newer versions.
Why not just load the variables twice then?
$questions = Question::with(['variables' => fn($v) => $v->where('type', '!=', 3)])->get();
// do whatever you need to do with the filtered collection
// reload variables relationship
$questions->load('variables');
// do whatever you need to do with the question and all its variables.
You can try
$questionsWithFilteredVariables = $questions->map(function($question) {
$variables = $question->variables->reject(fn($var) => $var->type === 3);
unset($question->variables);
$question->variables = $variables;
return $question;
});
//Now do json_decode(json_encode(...)), it will still contain filtered variables
$questionsWithFilteredVariables = json_decode(
json_encode($questionsWithFilteredVariables)
);

How to merge two queried results in Laravel Eloquent

I have a single form which I am using to create and edit information.
I am using Form::model to show all the data in the edit form which are queried from the database. Now I had to add another form part whose data is being stored in a different table. But I need to show those data during edit in the same form. I have tried to put two parameter in the form:model which did not work or I am doing it wrong.
{!! Form::model([$employee_data,$edu_info],['route'=>['employee.update',$employee_data->id],'method'=>'put','files'=> true]) !!}
Then I tried to merge the queried data in my controller like this:
public function edit($id)
{
$edit_info['title'] = 'Edit User';
$edit_info['country'] = Country::all();
$employee_basic = Employee::withTrashed()->where('id',$id)->first();
$employee_edu = EmployeeEdu::withTrashed()->where('employee_id',$id)->first();
$employee_all_data = $employee_basic->merge($employee_edu);
$employee_all_data->all();
$edit_info['employee_data'] = $employee_all_data;
return view('admin.employee.edit',$edit_info);
}
This did not work either. I get the following error:
Call to undefined method Illuminate\Database\Query\Builder::merge()
How can I achieve my intended result?
EDIT: I tried to use ->get() instead of ->first(), In this case I do not get the error but my merge does not work as when I dd($employee_all_data) it gives me only the value of $employee_edu.
Try this:
$employee_all_data = $employee_basic->toArray() + $employee_edu->toArray();

Laravel controller and adding to the result set

I've checked the Q&A about this and can't find anything, so thought i'd ask.
I have a very simple Laravel controller returning all results from a table as below via the 'Name model'. There is then also a further call to my controller, via the model to count the rows and all works and sends to the result set fine...
// All results from my 'Name' model:
$results = $this->name->getAllResults(); // All works fine.
// I then use my controller again, count the rows via the model and add them to $results:
$results['count'] = $this->countNames(); // Again fine
BUT, when i try to add a string to the $results array before i pass it off to th view, as in:
$results['test'] = 'Test'; // This fails in the view
$results['test'] = 124; // But this passes in the view and renders.
It only seems to allow me to add an INT to my result set array. as $results['test'] = 124 also fails.
I then finally, have this sending to my view via:
return view('names', compact('results')); // And that works fine.
Can anyone see what it is I am missing and why integer added to $results works and not a string?. Many thanks in advance.
You are updating collection data. The following line will give collection of models.
$results = $this->name->getAllResults(); // This may give collection of the model
And below, you are updating the collection object.
$results['count'] = $this->countNames();
You can do the following to safely send data to view, without modifying any.
$results = $this->name->getAllResults();
$count = $this->countNames();
$test = 'Test';
$test2 = 124;
return view('names', compact('results','count','test','test2'));

Laravel Debugger showing duplicated queries

Does any one has an idea about this. I don't know why it is showing duplicated queries. I searched a lot, found one answer on stackoverflow, but didn't get proper answer. If anyone faced the same error then please let me know. Thank you
protected $_param;
public function __construct(Utility $utility)
{
$league = $utility->checkDomainController();
view()->share('league', $league);
$this->league = $league;
}
This is the code in controller. which shares league to all the views. But there is only one query in $league = $utility->checkDomainController();
Here is the checkDomainController
if(\Request::server('HTTP_HOST') == env('MAIN_DOMAIN'))
{
$leagueSlug = Route::current()->getParameter('league');
$league = League::where('url', $leagueSlug)->first();
}
else
{
$league = League::where('custom_domain', \Request::server('HTTP_HOST'))->first();
}
if(!$league)
{
//error page
}
return $league;
Anytime you call a property which relies on a related model in blade, Laravel executes a new query, unless you eager load and pass from the controller to the view the preloaded data.
This example you posted seems to me as a loop somewhere within your blade code. Maybe if you can share a bit more of the code related to the front-end, I can help you figure it out.

How traverse model data from Controller in codeigniter

I am using codeigniter. From a model i have fetched some data in the controller using the following codes:
$data['english'] = $this->question_model->getRandomQuestions('english', 2);
So I know to access the data from view i would use the following code..
foreach($english as $eng){
echo $eng['columnName'];
}
But I want to travase the data in the controller doing some of my calculation. But how can I do that. I used the save above code in controller but it is then showing error.
The error message is as below :
Undefined variable: english
How can used those obtained data in controller using foreach loop. Any help would be appreciated...
thanx
Since the response is added in $data['english'] in your controller, then you would do:
foreach( $data['english'] as $i => $eng ) {
$data['english'][$i]['columnName'] = 'change with whatever';
}

Resources