Starting new query context in CodeIgniter's Active Record - codeigniter

I basically wanna do what I'd call nested queries (but not in the nested SELECT way) using CodeIgniter's Active Record.
So it would be like putting aside the current AR context to run a new query before restoring it.
A concrete example:
function handle_form($fields, $POST)
{
foreach ($fields as $field)
{
if ($field->type == "file")
do_upload($field->post); //This function does insert data in another table using AR too
$this->db->set($field->name, $POST[$field->post]);
}
$this->db->insert('table');
}
I haven't found any resources about that, maybe I'm just using the wrong keywords..
Thanks for your help !

function handle_form($fields, $POST)
{
$data = array();
foreach ($fields as $field)
{
if ($field->type == "file")
do_upload($field->post);
$data[$field->name] = $POST[$field->post];
}
$this->db->insert('table', $data);
}

Related

Create or update rows Laravel

I try to update or create a table with data from request, on update it works, but on create I can do just for 1. So, if I have 4 new items, just 1 is saved, not sure why, and no errors. If I dump the request I have all values.
$answers = new LkpAnswer;
foreach ($request->items as $key => $item) {
if (isset($item['id'])) {
$answers->where('id', $item['id'])->update($item);
} else {
$answers->fill($item)->save();
}
}
Please Try the following code:
foreach ($request->items as $key => $item) {
if (isset($item['id'])) {
LkpAnswer::where('id', $item['id'])->update($item);
} else {
$answers = new LkpAnswer; //new up an empty model(object) then fill it with your array of data, and finally save it.
$answers->fill($item)->save();
}
}
This should be achievable neatly with built in methods:
foreach ($request->items as $item) {
LkpAnswer::updateOrCreate($item['id'],$item);
}
Make sure that the relevant fields are fillable - see mass assignment protection.

Trying to remove all entries in a database who have specific query using Carbon

What I'm trying to achieve is I want to delete entries from my table who have are under 17 or minors. And that I want to remove also the parent table.
so this in my model
// Define the "age" property accessor.
public function getAgeAttribute()
{
return now()->diffInYears($this->birthdate);
}
and this is in my controller,
public function removeApplicanWhoAreNotAdults()
{
$date = Carbon::createFromDate(2001, 01, 01);
$todaysDate = Carbon::today();
$lastDay = $date->copy()->endOfYear();
$applicants = Applicant::whereBetween("birthdate", [$lastDay, $todaysDate])->get();
$applicants->each(function ($item, $key) {
});
}
Does the code on my controller suffice to the problem I'm trying to solve and How do i query applicants who have ages under 17 for example when my age is null in my db
Solution 1:
$applicant = Applicant::get();
foreach ($applicant as $key => $value) {
$year = now()->diffInYears($value->birthdate);
if($year > 17){
Applicant::where('id', $value->id)->delete();
}
}
Second way is first you have to create one command that way you can create proper programming and good way.
Follow this example
https://itsolutionstuff.com/post/example-of-cron-job-in-laravel-5example.html
Put above code in handel() method
public function handle()
{
$applicant = Applicant::get();
foreach ($applicant as $key => $value) {
$year = now()->diffInYears($value->birthdate);
if($year > 17){
Applicant::where('id', $value->id)->delete();
}
}
}

How to insert array data in laravel 5.4

I have a product table and device table.
I have joined these two tables where I have selected device.id & product.name, now I want to insert this data into my existing device table using device.id.
I want to insert multiple dropdown values in my database. Can anyone tell me how can I solve this problem? Below is my Controller Code-
foreach ($request->all() as $value)
{
$deviceById= Device::find($request->id);
if($request->destination_type == 'dealer')
{
$deviceById->destination_location=$value->dealer_id;
}else
{
$deviceById->destination_location=$value->office_id;
}
$deviceById->save();
}
flash('Device Dispatch added successfully!')->success()->important();
return redirect()->back();
You can make array of all dropdowns value and convert into a json string and store it in database
You can do something like this. Change according to your requirement. It just a logic demo.
$deviceById= Device::find($request->id);
$destination = array();
foreach ($request->all() as $value)
{
if($request->destination_type == 'dealer')
{
$destination[] = $value->dealer_id;
}else
{
$destination[] = $value->office_id;
}
}
$jsonString = json_encode($destination);
$deviceById->destination_location = $jsonString
$deviceById->save();
flash('Device Dispatch added successfully!')->success()->important();
return redirect()->back();
I solve it this way.I had used Elequent ORM
if($request->destination_type == 'Dealer')
{
DB::table('devices')
->whereIn('id',$request->device_list)
->update(['dealer_id'=>$request->destination_location,'device_status'=>"Dispatch"]);
flash('Device Dispatch dealer added successfully!')->success()->important();
}else
{
DB::table('devices')
->whereIn('id',$request->device_list)
->update(['office_id'=>$request->destination_location,'device_status'=>"Dispatch"]);
flash('Device Dispatch office added successfully!')->success()->important();
}

How to unset (remove) a collection element after fetching it?

I have a collection which I want to iterate and modify while I fetch some of its elements. But I could't find a way or method to remove that fetched element.
$selected = [];
foreach ($collection as $key => $value) {
if ($collection->selected == true) {
$selected[] = $value;
unset($value);
}
}
This is just a representation of my question for demonstration.
After #Ohgodwhy advice the forget() function I checked it again and saw that I actually misunderstood the function. It was exactly as I was looking for.
So for working solution I have added $collection->forget($key) inside the if statement.
Below is the working solution of my problem, using #Ohgodwhy's solution:
$selected = [];
foreach ($collection as $key => $value) {
if ($collection->selected == true) {
$selected[] = $value;
$collection->forget($key);
}
}
(this is just a demonstration)
You would want to use ->forget()
$collection->forget($key);
Link to the forget method documentation
Or you can use reject method
$newColection = $collection->reject(function($element) {
return $item->selected != true;
});
or pull method
$selected = [];
foreach ($collection as $key => $item) {
if ($item->selected == true) {
$selected[] = $collection->pull($key);
}
}
Laravel Collection implements the PHP ArrayAccess interface (which is why using foreach is possible in the first place).
If you have the key already you can just use PHP unset.
I prefer this, because it clearly modifies the collection in place, and is easy to remember.
foreach ($collection as $key => $value) {
unset($collection[$key]);
}
I'm not fine with solutions that iterates over a collection and inside the loop manipulating the content of even that collection. This can result in unexpected behaviour.
See also here: https://stackoverflow.com/a/2304578/655224 and in a comment the given link http://php.net/manual/en/control-structures.foreach.php#88578
So, when using foreach it seems to be ok but IMHO the much more readable and simple solution is to filter your collection to a new one.
/**
* Filter all `selected` items
*
* #link https://laravel.com/docs/7.x/collections#method-filter
*/
$selected = $collection->filter(function($value, $key) {
return $value->selected;
})->toArray();
If you know the key which you unset then put directly by comma
separated
unset($attr['placeholder'], $attr['autocomplete']);
You can use methods of Collection like pull, forget, reject etc.
But every Collection method returns an entirely new Collection instance.
Doc link: https://laravel.com/docs/8.x/collections#introduction

How to pass a view and a json from a function in laravel?

This is my function
if(isset($_POST['franchisesIds'])) {
$id_array = array();
foreach($_POST['franchisesIds'] as $data) {
array_push($id_array, (int)$data['id']);
}
$results = DB::table('franchises')->whereIn('id', $id_array)->get();
}
return Response::json(array($id_array));
return View::make('frontend.stores')->with('franchisesAll', $results);
So I am a little bit confused on how to pass all this data. I need to pass the json just to make sure everything worked. And at the same time I need to pass a list of ids to the view.
How can I do this??
Hopefully this is what you wanted :
Please don't use directly $_POST or $_GET instead use Input
$franchisesIds = Input::get('franchisesIds');
$id_array = array();
if($franchisesIds) {
foreach( $franchisesIds as $data) {
array_push($id_array, (int)$data['id']);
}
$results = DB::table('franchises')->whereIn('id', $id_array)->get();
}
$jsonArray = json_encode($id_array);
return View::make('frontend.stores')->with(array('franchisesAll'=>$results,'idArrays'=>$jsonArray));
In order to pass multiple values to the view, please read more about it in the official Laravel documentation
First of all you should use Input::get('franchisesIds') instead of $_POST['franchisesIds'], also there is no reason to do this foreach loop:
foreach($_POST['franchisesIds'] as $data) {
array_push($id_array, (int)$data['id']);
}
Because this is already an array and you are bulding another array from this array, makes no sense. So you may try this instead:
if($franchisesIds = Input::get('franchisesIds')) {
$franchises = DB::table('franchises')->whereIn('id', $franchisesIds)->get();
}
Then to pass both $franchisesIds and result to your view you may use this:
return View::make('frontend.stores')
->with('franchises', $franchises)
->with('franchisesIds', $franchisesIds);
You can also use something like this (compact):
return View::make('frontend.stores', compact('franchises', 'franchisesIds'));
There is no reason to use json_encode to encode your $franchisesIds.
You could also use
$results = DB::table('franchises')
->whereIn('id', $id_array)
->get()
->toJson();

Resources