multiple records in json update laravel database - php

I have a problem when going through my array, it only updates me just one record and I would like to act everything since I want the order to change in my table
public function updateAll(Request $request)
{
$questionOption1 = QuestionOption::all();
foreach ($questionOption1 as $item) {
$id=$item->id;
foreach ($request->all() as $order1) {
if ($order1['id'] == $id) {
$item->update(['order' => $order1['order']]);
}
}
return response('Update Successful.', 200);
}
// vuejs
eupdate() {
this.questionOptionNew.map((item,index)=>{
item.order = index + 1 ;
});
var url = '/api/update';
axios.post(url,this.questionOptionNew)
.then(response=>{
this.getQuestion();
});
console.log("hola",this.questionOptionNew);
},

Related

Efficient way to populate drop-down dynamically in laravel

I have multiple database tables which each one of them populates a dropdown, The point is each dropdown effects next dropdown.
I mean if I select an item from the first dropdown, the next dropdown values change on the selected item, which means they are related and they populate dynamically on each dropdown item change.
I know this is not efficient and need refactoring so I'd be glad to point me out to the right way of populating those dropdowns.
This is the controller code:
<?php
use App\Http\Controllers\Controller;
use App\Models\County;
use App\Models\OutDoorMedia;
use App\Models\Province;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
class FiltersController extends Controller
{
protected static $StatusCode = 0;
protected static $Msg = '';
protected static $Flag = false;
public function index(Request $request)
{
try {
$validator = Validator::make($request->all(), [
'province_id' => 'exists:province,id',
'county_id' => 'exists:county,id',
'media_type' => Rule::in([MEDIA_TYPE_BILLBOARD, MEDIA_TYPE_OUTDOOR_MONITOR, MEDIA_TYPE_INDOOR_MONITOR, MEDIA_TYPE_STAND, MEDIA_TYPE_STRABOARD, MEDIA_TYPE_BRAND_BOARD]),
'media_status' => Rule::in([MEDIA_STATUS_AVAILABLE, MEDIA_STATUS_NEGOTIATING, MEDIA_STATUS_ASSIGNED, MEDIA_STATUS_ARCHIVE]),
'category_id' => 'exists:category_list,id',
]);
if ($validator->fails()) {
abort(400, $validator->errors()->first());
} else {
//############################# Input Filters ####################################
$province_id = $request->has('province_id') ? $request->province_id : null;
$county_id = $request->has('county_id') ? $request->county_id : null;
$media_type = $request->has('media_type') ? $request->media_type : null;
$location = $request->has('location') ? $request->location : null;
$media_status = $request->has('media_status') ? $request->media_status : null;
$category_id = $request->has('category_id') ? $request->category_id : null;
//this flag is for detecting if user is requesting from "advertiser my order" to ignore some concitions
$advertiser_my_orders = ($request->has('my_orders') && $request->my_orders == 'true') ? true : false;
$province_ids = [];
$county_ids = [];
//############################# Media Owner Filters ####################################
//offline section filters
if (!is_null($province_id) && Province::whereId($request->province_id)->exists()) {
//check correction of county id
if (!is_null($county_id) && County::whereId($county_id)->whereProvinceId($province_id)->exists()) {
$media_owner_ODM_Provinces = Province::whereHas('media')->get()->toArray();
$media_owner_ODM_Provinces_Counties = County::whereProvinceId($province_id)
->whereHas('county_media')->get()->toArray();
foreach ($media_owner_ODM_Provinces as $key => $province) {
if ($province['id'] == $province_id) {
$media_owner_ODM_Provinces[$key]['county'] = $media_owner_ODM_Provinces_Counties;
}
}
$media_owner_ODM_locations = OutDoorMedia::whereProvinceId($province_id)->whereCountyId($county_id)->groupBy('location')->pluck('location')->toArray();
$media_owner_ODM_media_types = OutDoorMedia::whereProvinceId($province_id)->whereCountyId($county_id)->whereIn('location', $media_owner_ODM_locations)->groupBy('media_type')->pluck('media_type')->toArray();
$media_owner_ODM_media_Status = OutDoorMedia::whereProvinceId($province_id)->whereCountyId($county_id)->whereIn('media_type', $media_owner_ODM_media_types)->groupBy('status')->pluck('status')->toArray();
} else {
$media_owner_ODM_Provinces = Province::whereHas('media')->with(['county' => function ($query) {
$query->whereHas('county_media');
}])->get()->toArray();
$media_owner_ODM_locations = OutDoorMedia::whereProvinceId($province_id)->groupBy('location')->pluck('location')->toArray();
$media_owner_ODM_media_types = OutDoorMedia::whereProvinceId($province_id)->whereIn('location', $media_owner_ODM_locations)->groupBy('media_type')->pluck('media_type')->toArray();
$media_owner_ODM_media_Status = OutDoorMedia::whereProvinceId($province_id)->whereIn('media_type', $media_owner_ODM_media_types)->groupBy('status')->pluck('status')->toArray();
}
} else {
$media_owner_ODM_Provinces = Province::whereHas('media')->with(['county' => function ($query) {
$query->whereHas('county_media');
}])->get()->toArray();
foreach ($media_owner_ODM_Provinces as $province) {
$province_ids[] = $province['id'];
foreach ($province['county'] as $county) {
$county_ids[] = $county['id'];
}
}
$media_owner_ODM_locations = OutDoorMedia::whereIn('province_id', $province_ids)->whereIn('county_id', $county_ids)->groupBy('location')->pluck('location')->toArray();
$media_owner_ODM_media_types = OutDoorMedia::whereIn('province_id', $province_ids)->whereIn('county_id', $county_ids)->whereIn('location', $media_owner_ODM_locations)->groupBy('media_type')->pluck('media_type')->toArray();
$media_owner_ODM_media_Status = OutDoorMedia::whereIn('province_id', $province_ids)->whereIn('county_id', $county_ids)->whereIn('media_type', $media_owner_ODM_media_types)->groupBy('status')->pluck('status')->toArray();
}
$media_owner_offline = [
'provinces' => $media_owner_ODM_Provinces,
'media_status' => $media_owner_ODM_media_Status,
'location' => $media_owner_ODM_locations,
'media_type' => $media_owner_ODM_media_types,
];
$filters['media_owner']['offline'] = $media_owner_offline;
self::$StatusCode = 200;
self::$Msg = $filters;
self::$Flag = true;
}
} catch (\Exception $e) {
//=========== Get Error Exception Message ============
self::$StatusCode = 400;
self::$Msg = $e->getMessage();
self::$Flag = false;
return $this->CustomeJsonResponse(self::$Flag, self::$StatusCode, self::$Msg);
//=========== Get Error Exception Message ============
} finally {
return $this->CustomeJsonResponse(self::$Flag, self::$StatusCode, self::$Msg);
}
}
}
FYI: I'm using laravel 5.3 framework.
Here are something that you should be aware of them.
first of all, if you validate province_id, so there is no need to double check it in your code. so you should remove
Province::whereId($request->province_id)->exists()
Second one is, Laravel has ->when eloquent method that helps you reduce if else statements for null values, if we have a null value for given parameter, it will not effect the query.
https://laravel.com/docs/5.8/queries#conditional-clauses
Third one, I suggest you to use Laravel Resources in order to transform your fetched data from database in API.
https://laravel.com/docs/5.8/eloquent-resources
This is better version of small portion of your code, I think with suggested tips and this code, you can refactor it:
class TestController extends Controller
{
const DEFAULT_COUNTRY_ID = '10';
public $request;
public function something(Request $request)
{
// Put Validations ...
$this->request = $request;
OutDoorMedia::when('province_id', function ($query) {
return $query->where('province_id', $this->request->province_id);
})
->when('country_id', function ($query) {
// if country_id exists
return $query->where('country_id', $this->request->country_id);
}, function ($query) {
// else of above if (country_id is null ...)
return $query->where('country_id', self::DEFAULT_COUNTRY_ID);
})
->get();
}
}
This is just a sample, You can use this way to refactor your code base.

How to update whose status is 0 to 1?

I want to get all the user whose status is 0 and then update them to 1.
public function notification ()
{
$data = Ghar::where('status',0)->get();
foreach($data as $dat)
{
$id = $dat->id;
$aa['status'] = '1';
if(Ghar::find($id)->update($aa))
{
print_r('ok');
}
}
All these (same) answers can be narrowed down to:
$data = Ghar::whereStatus(0)->update(['status' => 1]);
Note: This doesn't trigger the update/save events as it is a mass update.
Try
public function notification ()
{
$data = Ghar::where('status',0)->get();
foreach($data as $dat)
{
$dat->status = 1;
$dat->save();
}
return
}
As you you have only getting data whose status is 0 and you want to set it to 1 which you can do simply by trying below code
public function notification ()
{
$data = Ghar::where('status',0)->get();
foreach($data as $dat)
{
// $dat is already a object of Ghar model so you don't need call find here you can simply do this
$dat->update(['status' => 1]);
}
}
Thanks

Optimizing collection filtering

I have 3 models: Account - Partner - User, with the 3 in belongsToMany relations (account_user, account_partner). I would like to filter all the User partners, authorized by the User accounts.
I have wrote the basic foreach loop hell, and I would like to ask for some tips for optimizing this filtering (like evading n+1 and other problems).
$userPartners = [];
foreach (auth()->user()->accounts as $account) {
foreach ($account->partners as $partner) {
$inList = false;
foreach ($userPartners as $userPartner) {
if ($userPartner->id === $partner->id) {
$inList = true;
}
}
if (!$inList) {
$userPartners[] = $partner;
}
}
}
dd($userPartners);
Start by eager loading your relationships with load. This will avoid the N+1 problem:
$user = auth()->user()->load('accounts');
$userPartners = [];
$user->accounts->each(function ($account) use ($userPartners) {
$ids = $account->partners->pluck('id');
if (!in_array($account->id, $ids)) {
$userPartners[] = $account->partners->where('id', $account->id);
}
});
You can do something like this:
Controller.php
$userPartners = collect();
auth()->user()->accounts->each(function($account) use ($userPartners) {
$account->partners->each(function($partner) use ($userPartners) {
if(!$userPartners->contains('id', $partner->id)) $userPartners->push($partner);
});
});
dd($userPartners);

export to excel file one specific row records

in laravel 5.1 using maatweb / Excel package i need to export specific row records to excel file where the current page id is viewing
in my VlistController
public function export()
{
Excel::create('Company List', function($excel)
{
$excel->sheet('companies', function($sheet)
{
$data = Vlist::all();
$data = json_decode(json_encode($data),true);
$companies = [];
foreach ($data as $key => $value) {
$company['vname']= $value['vname'];
$company['vaddress']= $value['vaddress'];
$companies[] = $company;
}
$sheet->fromArray($companies);
});
})->download('xlsx');
}
in my routes file
Route::get('/vlist/{vlist}/export' , 'VlistController#export');
in my show view
<li><i class='fa fa-link'></i> <span>Export Supplier : {!! $vlist->vname !!}</span></li>
the above controller code list all the records in excel sheet and i need only one specific record with the active id .
If I understand you problem,you can try this code.You can query by your primary key to retrieve specific row.
public function export($id)
{
Excel::create('Company List', function($excel) use ($id)
{
$excel->sheet('companies', function($sheet) use ($id)
{
$data = Vlist::where('id', $id)->get();
$data = json_decode(json_encode($data),true);
$companies = [];
foreach ($data as $key => $value) {
$company['vname']= $value['vname'];
$company['vaddress']= $value['vaddress'];
$companies[] = $company;
}
$sheet->fromArray($companies);
});
})->download('xlsx');
}
and I don't think the following code is necessary.
$data = json_decode(json_encode($data),true);
$companies = [];
foreach ($data as $key => $value) {
$company['vname']= $value['vname'];
$company['vaddress']= $value['vaddress'];
$companies[] = $company;
}
You can simply use the retrieve specific data
$data = Vlist::where('id', $id)->get(['vname', 'vaddress']);
and pass it to the method
$sheet->fromArray($data);
Thanks
I am in not sure about your Question, in my point of view you want to put(show) record form a specified row then my solution will work.
$projectArr[] = ["col1","col2","col3","col4","col5","col6"];
Excel::create('project_directory_result_sheet', function($excel) use($projectArr) {
$excel->sheet('Project_Directory_Result', function($sheet) use( $projectArr ) {
$sheet->fromArray($projectArr,null, 'A3');
}
}
In my solution noticeable point is $sheet->fromArray($projectArr,null, 'A3');
here i am giving 3 parameter value that are
first:Project Value Array.
second: show header true or false
third: row number where you want to represent record.

Accessing php variables outside of a method in a function

I'm not understanding why this is not working?
I am working in php and specifically laravel.
When I run it I get an undefined variable exception.
I would think I would get the array of bad_rows?
Also on a side question, how could I refactor this to be cleaner? Should I extract the Excel method to its own function?
I basically am trying to import the list, add it to the database and then I will redirect to the main page with the list of rows that were not imported by flashing it.
Thanks!
public function subscriberImportList(Request $request)
{
\Excel::filter('chunk')->load($request->file('import_list'))->chunk(100, function($rows) use($request)
{
$bad_rows = [];
foreach($rows as $row)
{
if (is_null($row->name) || is_null($row->street_address) || is_null($row->city)){
array_push($bad_rows, $row->name);
}
else {
//New Subscriber Instance
$subscriber = new Subscriber;
//Set the name
$subscriber->name = $row->name;
//Set the street address
$subscriber->street_address = $row->street_address;
//Set the city,state zip
preg_match('/([^,]+),\s*(\w{2})\s*(\d{5}(?:-\d{4})?)/', $row->city, $city_state_zip_seperated);
if (!$city_state_zip_seperated) {
array_push($bad_rows, $row->name);
}
else {
$subscriber->city = $city_state_zip_seperated[1];
$subscriber->state = $city_state_zip_seperated[2];
$subscriber->zipcode = $city_state_zip_seperated[3];
//Persist the subscriber to the database
$subscriber->save();
}
}
}
return $bad_rows;
});
dd($bad_rows);
}
You have:
public function subscriberImportList(Request $request) {
\Excel::[..snip..], function($rows) use($request) {
$bad_rows = [];
^^^^^^^^^^------defined here
blah blah blah
});
dd($bad_rows);
^^^^^^^^---used here
}
$bad_rows is only ever defined INSIDE that function($rows) closure, which means it's a local variable inside the closure, and exists nowhere else. So when you try dd($bad_rows), you are using an undefined variable.
What you should have is
public function .... {
$bad_rows = [];
^^^^^^^^^^^^^^^^
\Exce..... function($row) use($request, $bad_rows) {
^^^^^^^^^^^^
blah blah blah
});
dd($bad_rows);
}

Categories