How to add laravel query function lists in updateOrCreate eloquent - php

I am trying to use updateOrCreate with multiple conditions and this condition can be applied occasionally if corresponding data are available. I am currently doing as first find the id if exists and if id exists update else create manually but now i want to use laravel given updateOrCreate function.
$existing = Student::where('name_last', $student['name_last'])
->where('name_first', $student['name_first'])
->where(function($query) use ($student) {
if (array_key_exists('phone_preferred', $student) && !empty($student['phone_preferred'])) {
$query->where('phone_preferred', $student['phone_preferred']);
}
if (array_key_exists('email_preferred', $student) && !empty($student['email_preferred'])) {
$query->where('email_preferred', $student['email_preferred']);
}
if (array_key_exists('home_street_address_1', $student) && !empty($student['home_street_address_1'])) {
$query->where('home_street_address_1', $student['home_street_address_1']);
}
if (array_key_exists('mailing_street_address_1', $student) && !empty($student['mailing_street_address_1'])) {
$query->where('mailing_street_address_1', $student['mailing_street_address_1']);
}
if (array_key_exists('mailing_address_city', $student) && !empty($student['mailing_address_city'])) {
$query->where('mailing_address_city', $student['mailing_address_city']);
}
})->first();
if($existing){
try{
Student::where('id', $existing->id)
->update($student);
} catch (\Exception $e) {
$error_encountered = true;
$error_arr[] = $e->getMessage();
$error_row_numbers[] = $row_no;
}
}
I want to implement with something like:
try{
Student::updateOrCreate(
['name_first' => $student['name_first], 'name_last' => $student['name_last]],
$student
); //I could not get how to implement other occasional where condition
} catch (\Exception $e) {
$error_encountered = true;
$error_arr[] = $e->getMessage();
$error_row_numbers[] = $row_no;
}
I want to include those occasional where function query to updateOrCreate method which is currently implementing in manual method

You can just add all the attributes you want to check for in the array that you pass to updateOrCreate
// these are your required conditions
$conditions = [
'name_first' => $student['name_first'],
'name_last' => $student['name_last'],
];
// these are optional
$attributes = [
'phone_preferred',
'email_preferred',
'home_street_address_1',
'mailing_street_address_1',
'mailing_address_city'
];
foreach($attributes as $attr){
// check to see if the attribute exists on the student
// and is not empty
if(isset($student[$attr]) && !empty($student[$attr])){
$conditions[$attr] = $student[$attr];
}
}
Student::updateOrCreate($conditions);

Related

Laravel 8 not finding "tag" from package "\Conner\Tagging\Taggable;"

The code works perfectly when I want to create a new tag from scratch, but when $skillsQuery->count() > 0 and enters in the if statement. It prints...
Method Illuminate\Database\Eloquent\Collection::tag does not exist.
How can I update tags using this package?
Controller
<?php
public function storeSkills(Request $request)
{
$id = auth()->user()->id;
$skillsQuery = Skill::where('created_by', $id)->get();
// If skill exists
if ($skillsQuery->count() > 0) {
$input = $request->all();
$tags = explode(", ", $input['name']);
// $skill = Skill::create($input);
$skillsQuery->tag($tags);
$skillsQuery->created_by = $id;
if ($skillsQuery->save()) {
return redirect()->route('profile')->with('success', 'Skills updated successfully');
} else {
return redirect()->route('profile')->with('error', 'Error updated your Skills!');
}
} else {
$input = $request->all();
$tags = explode(", ", $input['name']);
$skill = Skill::create($input);
$skill->tag($tags);
$skill->created_by = $id;
if ($skill->save())
return redirect()->route('profile')->with('success', 'Skills stored successfully');
else {
return redirect()->route('profile')->with('error', 'Error storing your Skills!');
}
}
}
The result of calling ->get() on a Illuminate\Database\Query is that you will receive an instance of a Illuminate\Database\Collection, which does not contain a ->tag() method. Even if it was a query (by removing ->get()) this still would not work, as you can't call a relationship method off of a collection.
If instead you loop over the skillsQuery then you will receive an instance of a Model object which then allows you to access functions and/or relationships off of it:
$skillsQuery->each(function ($skill) use ($tags) {
$skill->tag($tags); // or perhaps ->retag($tags); here
});

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.

If condition on save laravel

I had 2 tables. driver and part_time_available in the same form, when I select driver type = parttime, it'll show part_time_available field(day, start_time, end_time).
How to make condition if user choose fulltime. it didn't store part_time_available field to database.
here's my savehandler code so far :
public function saveHandler(Request $request, $obj)
{
try {
DB::beginTransaction();
$obj->fill($request->all());
if (!$obj->save()) {
throw new ValidationException($obj->errors());
}
foreach($request->parttimeAvailabilities as $pta) {
\Log::info($pta);
if (empty($pta['id'])) {
$parttimeAvailability = new PartTimeAvailability();
}
else {
$parttimeAvailability = PartTimeAvailability::find($pta['id']);
}
$parttimeAvailability->driver()->associate($obj);
$pta['driver_id'] = isset($pta['driver_id']);
$parttimeAvailability->day = $pta['day'];
$parttimeAvailability->start_time = isset($pta['start_time']) ? $pta['start_time'] : '00:00:00';
$parttimeAvailability->end_time = isset($pta['end_time']) ? $pta['end_time'] : '00:00:00';
$parttimeAvailability->available = isset($pta['available']);
$parttimeAvailability->save();
};
$obj->save();
if (!$parttimeAvailability->save()) {
throw new ValidationException($parttimeAvailability->errors());
}
DB::commit();
return $this->sendSuccessResponse($request);
} catch (ValidationException $e) {
DB::rollback();
\Log::error($e->errors);
return $this->sendErrorResponse($request, $e->errors);
} catch (Exception $e) {
DB::rollback();
\Log::error($e->getMessage());
return $this->sendErrorResponse($request,'Unable to process. Please contact system Administrator');
}
}
I mean before running foreach, it needs to check it's parttime or not.
any idea ?
You can give a condition before the whole foreach loop. such as:
if($request->get('driver_type') != 'full_time'){
foreach loop
}

Yii2 Dynamic forms action update get error

I have two models in my Yii2 application :
Racks(rackID,rowID,...)
RackObjects(rack_objectID,rackID,objectID,...)
In my racksController I have :
public function actionUpdate($id)
{
$model = $this->findModel($id);
$modelsRackObjects = $model->rackObjects;
if ($model->load(Yii::$app->request->post())) {
$oldIDs = ArrayHelper::map($modelsRackObjects, 'rack_objectID', 'rack_objectID');
$modelsRackObjects = Racks::createMultiple(RackObjects::classname(), $modelsRackObjects);
Racks::loadMultiple($modelsRackObjects, Yii::$app->request->post());
$deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsRackObjects, 'rack_objectID', 'rack_objectID')));
// validate all models
$valid = $model->validate();
$valid = Racks::validateMultiple($modelsRackObjects) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
if (!empty($deletedIDs)) {
Racks::deleteAll(['rackID' => $deletedIDs]);
}
foreach ($modelsRackObjects as $modelRackObjects) {
$modelRackObjects->rackID = $model->rackID;
if (! ($flag = $modelRackObjects->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->rackID]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
}
return $this->render('update', [
'model' => $model,
'modelsRackObjects' => (empty($modelsRackObjects)) ? [new RackObjects] : $modelsRackObjects
]);
}
And in my "Racks Model" I have :
public static function createMultiple($modelClass, $multipleModels = [])
{
$model = new $modelClass;
$formName = $model->formName();
$post = Yii::$app->request->post($formName);
$models = [];
if (! empty($multipleModels)) {
$keys = array_keys(ArrayHelper::map($multipleModels, 'rack_objectID', 'rack_objectID'));
$multipleModels = array_combine($keys, $multipleModels);
}
if ($post && is_array($post)) {
foreach ($post as $i => $item) {
if (isset($item['rack_objectID']) && !empty($item['rack_objectID']) && isset($multipleModels[$item['rack_objectID']])) {
$models[] = $multipleModels[$item['rack_objectID']];
} else {
$models[] = new $modelClass;
}
}
}
unset($model, $formName, $post);
return $models;
}
When I update the racks form and change some rackObjects I get this error :
Integrity constraint violation – yii\db\IntegrityException
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails
What is wrong in my action update???
I changed my codes thanks to this answer and now when I update records the child table (rackObjects) duplicated and old records was not deleted!! any idea?
deleteAll() will not raise the beforeDelete event. You should loop through:
$racks = Rack::findAll(['rackID' => $deletedIDs]);
foreach($racks as $rack) {
$rack->delete();
}
And in Rack model, assuming you have hasMany relationship with RackObjects
public function beforeDelete() {
if (parent::beforeDelete()) {
foreach($this->rackObjects as $rackObj) {
$rackObj->delete();
}
return true;
} else {
return false;
}
}

Doctrine: How to save only collection items that do not exist in DB yet

I have a collection of items to save to database, but I want the record to be inserted only if not exists.
I think the most effective way would be to filter the collection before saving. Can Doctrine do it automatically?
Or shall I get all id's of all items in the collection, then query the database for items which do not exists on the list of these id's, then in foreach remove all collection items which we do not need, and finally save collection?
Any better approach suggested?
This is the save function from the Doctrine_Collection class
public function save(Doctrine_Connection $conn = null, $processDiff = true)
{
if ($conn == null) {
$conn = $this->_table->getConnection();
}
try {
$conn->beginInternalTransaction();
$conn->transaction->addCollection($this);
if ($processDiff) {
$this->processDiff();
}
foreach ($this->getData() as $key => $record) {
$record->save($conn);
}
$conn->commit();
} catch (Exception $e) {
$conn->rollback();
throw $e;
}
return $this;
}
I'm not sure where you are getting your collection from, or if you are manually building it, but you might want to try extending the Doctrine_Collection class and overloading the save function like this
<?php
class My_Collection extends Doctrine Collection
{
public function save(Doctrine_Connection $conn = null, $processDiff = true, $createOnly = true)
{
if ($conn == null) {
$conn = $this->_table->getConnection();
}
try {
$conn->beginInternalTransaction();
$conn->transaction->addCollection($this);
if ($processDiff) {
$this->processDiff();
}
foreach ($this->getData() as $key => $record) {
if($createOnly)
{
if ($record->exists())
{
$record->save($conn);
}
}else{
$record->save($conn);
}
}
$conn->commit();
} catch (Exception $e) {
$conn->rollback();
throw $e;
}
return $this;
}
}
I don't know anything about Doctrine, but the MySQL REPLACE query does just what you want - updates existing rows & creates new rows if no primary key matches were found.

Categories