Push into session issue in Laravel - laravel

Each item contains a list of addons as checkboxes. Every time I check an addon I want to push addon_id into the addons array. It's pushing an addon_id to session but it's not pushing it properly.
This code adds item to cart (Notice: I am creating an empty addons array):
$cart = session()->get('cart', []);
if(isset($cart[$request->item_id])) {
$cart[$request->item_id]['qty']++;
} else {
$cart[$request->item_id] = [
'id' => $request->item_id,
'category_id' => $request->category_id,
'price' => $request->item_price,
'item_name' => $request->item_name,
'qty' => 1,
'addons' => [],
];
}
session()->put('cart', $cart);
And this code pushes addons to items:
if(isset($request->item_id)) {
session()->push('cart.addons', $request->addon_id);
}
$cart = session()->get('cart', []);
return response()->json([
'message' => 'Addon added',
'cart' => $cart,
]);
This is how addons are being pushed now:
Array
(
[59] => Array
(
[id] => 59
[category_id] => 27
[price] => 3.78
[item_name] => Simple Sandwich
[qty] => 1
[addons] => Array
(
)
)
[57] => Array
(
[id] => 57
[category_id] => 27
[price] => 5.99
[item_name] => Cheese Burger
[qty] => 1
[addons] => Array
(
)
)
[addons] => Array
(
[0] => 31
)
[addons] => Array
(
[0] => 61,
[1] => 60,
[2] => 31
)
)
I need them to be pushed like this:
Array
(
[59] => Array
(
[id] => 59
[category_id] => 27
[price] => 3.78
[item_name] => Simple Sandwich
[qty] => 1
[addons] => Array
(
[0] => 31
)
)
[57] => Array
(
[id] => 57
[category_id] => 27
[price] => 5.99
[item_name] => Cheese Burger
[qty] => 1
[addons] => Array
(
[0] => 61,
[1] => 60,
[2] => 31
)
)
)
I tried to find a solution but nothing seems to be working the way I need it.
Help is very much appreciated.

Initially you are making an associative array where item_id is the key, but when you are appending in addons you are not specifying against which item_id the addons array should be updated, so you will have to change
if(isset($request->item_id)) {
session()->push('cart.addons', $request->addon_id);
}
to something like this:
if(isset($request->item_id)) {
$cart = session()->get('cart');
if(isset($cart[$request->item_id]) {
array_push($cart[$request->item_id]['addons'],$request->addon_id);
session()->put('cart',$cart);
}
}

Related

How can I check that file returned by laravel-medialibrary getUrl method really exists?

In laravel 8 app I use spatie/laravel-medialibrary 9
and how can I check that file returned by getUrl really exists under storage in code :
foreach (Auth::user()->getMedia('avatar') as $mediaImage) {
\Log::info( varDump($mediaImage, ' -1 $mediaImage::') );
return $mediaImage->getUrl();
}
?
$mediaImage var has data like:
Array
(
[id] => 11
[model_type] => App\Models\User
[model_id] => 1
[uuid] => 2fb4fa16-cbdc-4902-bdf5-d7e6d738d91f
[collection_name] => avatar
[name] => b22de6791bca17184093c285e1c4b4b5
[file_name] => avatar_111.jpg
[mime_type] => image/jpg
[disk] => public
[conversions_disk] => public
[size] => 14305
[manipulations] => Array
(
)
[custom_properties] => Array
(
)
[generated_conversions] => Array
(
)
[responsive_images] => Array
(
)
[order_column] => 1
[created_at] => 2021-12-30T14:08:11.000000Z
[updated_at] => 2021-12-30T14:08:11.000000Z
[original_url] => http://127.0.0.1:8000/storage/Photos/11/avatar_111.jpg
[preview_url] =>
)
Looks like nothing about file under storage...
Thanks!
Method :
File::exists($mediaImage->getPath());
helped me!

Laravel Model Binding missing relationships

I'm trying to convert to Model binding on a Model built on customer orders. My route:
Route::model('order', 'App\Models\Order');
Route::resource('orders', 'OrderController');
This allows me to pull up an Order to edit through my controller (also grabbing statuses to populate a table and passing the logged in user):
public function index(Order $order)
{
$orders = $order->get();
return view('orders.index', compact('orders'));
}
My orders.index will display $order->id properly but when I try to loop through the Actions, which is connected by a hasMany relationship, nothing shows. Or I try to show $order->user->firstname which belongs to User by user_id.
#foreach( $order->actions as $action )
{{ $action->type->type }}
#endforeach
From my Action model:
public function order()
{
return $this->belongsTo('\App\Models\Order', 'order_id');
}
From my Order model:
public function actions()
{
return $this->hasMany('\App\Models\Action', 'order_id');
}
Here's an excerpt from a dump of the Order:
`Illuminate\Database\Eloquent\Collection Object
(
[items:protected] => Array
(
[0] => App\Models\Order Object
(
[table:protected] => orders
[timestamps] => 1
[dates:protected] => Array
(
[0] => deleted_at
)
[connection:protected] =>
[primaryKey:protected] => id
[perPage:protected] => 15
[incrementing] => 1
[attributes:protected] => Array
(
[id] => 1
[created_at] => 2015-03-16 23:42:45
[updated_at] => 2015-03-19 04:37:53
[deleted_at] =>
[user_id] => 16
[status_id] => 5
[address_id] => 5
[datetime_pickup_actual] =>
[datetime_delivery_actual] =>
[datetime_pickup_requested] => 2015-03-20 17:00:00
[datetime_delivery_requested] => 2015-03-21 17:00:00
[hold] => 0
[weight] => 20
)
[original:protected] => Array
(
[id] => 1
[created_at] => 2015-03-16 23:42:45
[updated_at] => 2015-03-19 04:37:53
[deleted_at] =>
[user_id] => 16
[status_id] => 5
[address_id] => 5
[datetime_pickup_actual] =>
[datetime_delivery_actual] =>
[datetime_pickup_requested] => 2015-03-20 17:00:00
[datetime_delivery_requested] => 2015-03-21 17:00:00
[hold] => 0
[weight] => 20
)
[relations:protected] => Array
(
)
[hidden:protected] => Array
(
)
[visible:protected] => Array
(
)
[appends:protected] => Array
(
)
[fillable:protected] => Array
(
)
[guarded:protected] => Array
(
[0] => *
)
[casts:protected] => Array
(
)
[touches:protected] => Array
(
)
[observables:protected] => Array
(
)
[with:protected] => Array
(
)
[morphClass:protected] =>
[exists] => 1
[forceDeleting:protected] =>
)`
As you compact orders in your controller you should use orders in your Blade template:
#foreach( $orders->actions as $action )
{{ $action->type->type }}
#endforeach
You should be also aware that Order in your index method in controller have nothing in common with Route Model Binding. For index it won't be used at all.
For other methods (show/edit/delete) it won't work because you make a binding with wrong name. It should be:
Route::model('orders', 'App\Models\Order');
and not
Route::model('order', 'App\Models\Order');
Model name (MoneyEntry)
Changed from
Route::resource('moneyentries', 'MoneyEntryController');
to
Route::resource('moneyEntries', 'MoneyEntryController');
Did a trick.

How to apply filter on pivot table in laravel?

I have three models with the following relations
MODEL-1: RecoringSchedule
protected $recording_schedule = 'recording_schedules';
// relationship with processes
public function processes()
{
return $this->belongsToMany('Process', 'recording_uploads', 'recording_schedule_id', 'process_id');
}
MODEL-2: Process
protected $table = 'processes';
// relationship with recordings
public function recordings()
{
return $this->belongsToMany('RecordingSchedule', 'recording_uploads');
}
MODEL-3: RecordingUpload
protected $table = 'recording_uploads';
Here model3 is the pivot table which contains id, recording_schedule_id, process_id, created_at, updated_at
I have a query,
$recordings = RecordingSchedule::with('processes')->orderBy('recording_date_time', 'desc')->paginate(50)->toArray()
The above query is return all the recordings with process.
Now how can I apply filter by process_id which is in pivot table?
like where process_id = 3
I have tried Kousha answer
It is displaying
[id] => 35
[dialin_number] => 9908154124
[operator_extension] => 121
[recording_id] => 08631a03109
[max_duration] => 10
[recording_date_time] => 2014-07-31 13:06:00
[status] => ADDED
[created_by] => 32
[created_at] => 2014-07-31 12:06:48
[updated_at] => 2014-07-31 12:14:04
[processes] => Array
(
[0] => Array
(
[id] => 3
[name] => basic
[created_at] => 2014-07-10 12:22:06
[updated_at] => 2014-07-16 14:06:35
[pivot] => Array
(
[recording_schedule_id] => 35
[process_id] => 3
)
)
)
and also other recordings as below
[id] => 39
[dialin_number] => 939938333
[operator_extension] => 141
[recording_id] => 123456#
[max_duration] => 30
[recording_date_time] => 2014-07-31 12:19:00
[status] => ADDED
[created_by] => 32
[created_at] => 2014-07-31 13:20:16
[updated_at] => 2014-07-31 13:20:34
[processes] => Array
(
)
)
In the second array recording with empty processes are displaying. Actually that recording belongs to process id 6. I don't want other recordings with other process id.
Thanks in advance
You don't apply the filter on the pivot, but on the table processes:
$process_id = 3;
$recordings = RecodingsSchedule::with([
'processes' => function($query) use ($process_id)
{
$query->whereId($process_id);
}
])->orderBy('recording_date_time', 'desc')->paginate(50)->toArray();

Deleting categories in magento

I want to delete empty categories, using the following code:
`<?php
require "app/Mage.php";
umask(0);
Mage::app();
$categoryCollection = Mage::getModel('catalog/category')->getCollection()->addFieldToFilter('level', array('gteq' => 2));
foreach($categoryCollection as $category) {
if ($category->getProductCount() === 0) {
print_r ($category);
echo "<br><hr><br>";
$category->delete();
}
}
echo 'End!';
?>`
Upon executing this code, it crashes at delete.
print_r gives the following result:
Mage_Catalog_Model_Category Object (
[_eventPrefix:protected] => catalog_category
[_eventObject:protected] => category
[_cacheTag:protected] => catalog_category
[_useFlatResource:protected] => 1
[_designAttributes:Mage_Catalog_Model_Category:private] => Array (
[0] => custom_design
[1] => custom_design_from
[2] => custom_design_to
[3] => page_layout
[4] => custom_layout_update
[5] => custom_apply_to_products
)
[_treeModel:protected] =>
[_defaultValues:protected] => Array (
)
[_storeValuesFlags:protected] => Array (
)
[_lockedAttributes:protected] => Array (
)
[_isDeleteable:protected] => 1
[_isReadonly:protected] =>
[_resourceName:protected] => catalog/category_flat
[_resource:protected] =>
[_resourceCollectionName:protected] => catalog/category_flat_collection
[_dataSaveAllowed:protected] => 1
[_isObjectNew:protected] =>
[_data:protected] => Array (
[entity_id] => 53
[level] => 4
[path] => 1/2/27/39/53
[position] => 3
[is_active] => 1
[is_anchor] => 1
[product_count] => 0
)
[_hasDataChanges:protected] => 1
[_origData:protected] => Array (
[entity_id] => 53
[level] => 4
[path] => 1/2/27/39/53
[position] => 3
[is_active] => 1
[is_anchor] => 1
)
[_idFieldName:protected] => entity_id
[_isDeleted:protected] =>
[_oldFieldsMap:protected] => Array (
)
[_syncFieldsMap:protected] => Array (
)
)
What am I doing wrong, and how should I do it?
Any help would be greatly appreciated.
<?php
require "app/Mage.php";
umask(0);
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
$categoryCollection = Mage::getModel('catalog/category')->getCollection()->addFieldToFilter('level', array('gteq' => 2));
foreach($categoryCollection as $category) {
if ($category->getProductCount() === 0) {
print_r ($category->entity_id);
echo "<br><hr><br>";
$category->delete();
}
}
echo 'End!';
?>
You have to add this line
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
you write this code print_r ($category); so its reruns the array. That is not error.

CodeIgniter Multidimensional Object - ActiveRecord

I have an object called 'events', that's created via $data['events'] = function (the function pulls information out of an events table and others using active record).
The events object looks like:
Array
(
[0] => stdClass Object
(
[id] => 2
[course_name] => Course 3
[course_description] => Course
[course_price] => 995
[supplier_name] => Supplier 3
[location_country_code] => GB
[location_country] => United Kingdom
[location_city] => London
[venue_name] => Venue 2
[venue_address] => 2 Street
[venue_postcode] => EC2M 7PQ
[venue_city] => London
[venue_county] =>
[venue_country] => United Kingdom
[venue_locality] =>
[event_type] => Materials Only
[event_status] => Confirmed
[course_id] => 2
[event_duration] => 3
[event_start_date] => 2013-09-12
[event_date_added] => 2013-02-26 14:36:06
[event_status_id] => 2
[event_type_id] => 4
[tutor_id] => 0
[tutor_confirmed] => 0
[event_featured] => 0
[event_push] => 0
[event_active] => 0
[invigilator_id] => 0
[event_discount] =>
[event_max_delegates] => 16
[location_id] => 1
[venue_id] => 1
[supplier_id] => 2
)
[1] => stdClass Object
(
[id] => 1
[course_name] => Course Name
[course_description] => Course Description
[course_price] => 995
[supplier_name] => Supplier 1
[location_country_code] => GB
[location_country] => United Kingdom
[location_city] => London
[venue_name] => Venue Name
[venue_address] => Street
[venue_postcode] => EC2M 7PQ
[venue_city] => London
[venue_county] =>
[venue_country] => United Kingdom
[venue_locality] =>
[event_type] => Private Venue
[event_status] => Provisional
[course_id] => 1
[event_duration] => 3
[event_start_date] => 2013-11-13
[event_date_added] => 2013-02-26 09:56:17
[event_status_id] => 1
[event_type_id] => 3
[tutor_id] => 0
[tutor_confirmed] => 0
[event_featured] => 0
[event_push] => 0
[event_active] => 0
[invigilator_id] => 0
[event_discount] => 395
[event_max_delegates] => 16
[location_id] => 1
[venue_id] => 1
[supplier_id] => 1
)
)
I'd like to add a nested object under the key 'delegates' for each row using ActiveRecord, that pulls through the delegates attached to the event using a bridge table 'events_delegates_bridge' by comparing the 'event_id' and 'delegate_id columns in that table.
Essentially so that the object looks like so:
Array
(
[0] => stdClass Object
(
[id] => 2
[course_name] => Course 3
[delegates] => Array
(
[0] => stdClass Object
(
[id] => 1
[name] => Joe Bloggs
)
[1] => stdClass Object
(
[id] => 2
[name] => Joe Smith
)
[3] => stdClass Object
(
[id] => 3
[name] => Jane Doe
)
)
[course_description] => Course
[course_price] => 995
[supplier_name] => Supplier 3
[location_country_code] => GB
[location_country] => United Kingdom
[location_city] => London
[venue_name] => Venue 2
[venue_address] => 2 Street
[venue_postcode] => EC2M 7PQ
[venue_city] => London
[venue_county] =>
[venue_country] => United Kingdom
[venue_locality] =>
[event_type] => Materials Only
[event_status] => Confirmed
[course_id] => 2
[event_duration] => 3
[event_start_date] => 2013-09-12
[event_date_added] => 2013-02-26 14:36:06
[event_status_id] => 2
[event_type_id] => 4
[tutor_id] => 0
[tutor_confirmed] => 0
[event_featured] => 0
[event_push] => 0
[event_active] => 0
[invigilator_id] => 0
[event_discount] =>
[event_max_delegates] => 16
[location_id] => 1
[venue_id] => 1
[supplier_id] => 2
)
)
Any ideas how best to achieve this? Thanks.
Event Model
class Event_Model extends CI_Model {
public function get_events() {
$this->db->select( '*' );
$this->db->from( 'courses' );
$this->db->from( 'suppliers' );
$this->db->from( 'locations' );
$this->db->from( 'venues' );
$this->db->from( 'event_type' );
$this->db->from( 'event_status' );
$this->db->join( 'events', 'events.course_id = courses.id AND events.supplier_id = suppliers.id AND events.location_id = locations.id AND events.venue_id = venues.id AND events.event_type_id = event_type.id AND events.event_status_id = event_status.id', 'inner' );
$this->db->order_by( 'events.event_start_date', 'asc' );
$query = $this->db->get();
return $query->result();
}
}
Dashboard Controller
$data['events'] = $this->event_model->get_events();
Delegates Model
I've created this to get the delegate data. Do you think it can be used to add the correct delegates to the events object?
class Delegate_Model extends CI_Model {
public function get_delegates() {
$this->db->select( '*' );
$this->db->from( 'delegates' );
$this->db->from( 'events_delegates_bridge' );
$this->join( 'delegates', 'delegates.id = events_delegates_bridge.delegate_id', 'inner' );
$query = $this->db->get();
return $query->result();
}
}
Just tested this and it shows a blank page.
You're best off doing it with 2 separate queries.
$events = array();
$result = $this->db->query('SELECT * FROM events WHERE ...');
foreach($result->result_array() as $event) {
$events[$event['id']] = $event;
}
$result = $this->db->query('
SELECT * FROM events_delegates_bridge
JOIN delegates ON (delegate_id = delegates.id)
WHERE ...
');
foreach($result->result_array() as $delegate) {
if (!empty($events[$delegate['event_id']])) {
$events[$delegate['event_id']]['delegates'][] = $delegate
}
}
This bit of code just queries the events and puts them in an array indexed by the event id.
Then, a separate query runs to pull up the delegates, and attaches them to the appropriate event.
use $name=$variable->result_array();var_dump($name); I think This work

Resources