displaying particular data from entire json using laravel - laravel

I have an issue in printing the data from the below json in laravel. Find below the json data and help me with this.
DarthSoup\Cart\Item Object ( [rowId] => 76cc22e6f533b8ef3d08e6eca0f110b4 [id] => 61XJrpB7CgiYSRCX6hR78wCEABhjLI7jNLzPyDrkYA3LyIVisz [name] => linux [quantity] => 1 [price] => 109 [options] => DarthSoup\Cart\CartItemOptions Object ( [items:protected] => Array ( [package] => Super Lite ) ) [subItems] => DarthSoup\Cart\SubItemCollection Object ( [items:protected] => Array ( ) ) [created_at:protected] => Carbon\Carbon Object ( [date] => 2018-06-22 05:41:18.674548 [timezone_type] => 3 [timezone] => UTC ) [updated_at:protected] => Carbon\Carbon Object ( [date] => 2018-06-22 05:41:18.674574 [timezone_type] => 3 [timezone] => UTC ) [associatedModel:protected] => [taxRate:protected] => 19 ) 1
From the above json how to display the "price=>109" and "package=>super Lite"...
I'm getting an error as "Cannot use object of type DarthSoup\Cart\Item as array"
Find below the controller Code:
public function addCart(Request $request)
{
$name = $request->input();
$hosting=$name['hosting'];
$package=$name['package'];
$price=$name['price'];
$response=Cart::add(['id'=>str_random(50) ,'name' => $hosting, 'quantity' => 1, 'price' => $price, 'options' => ['package' => $package]]);
//dd($response);
return Cart::content();
return view('main.cart',Cart::content());
}
Blade file is given below:
#foreach($response->options as $option){
{{$option['name']}}
}
#endforeach
In my output I need to display the value of price,name and package...please help me to solve this error...

First this is not json, it is php object
if your variable name is $item then you can try this
$item->rowId;
$item->id;
$item->name;
$item->price;
foreach($item->options as $option){
echo $option->package;
}

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!

Unable to access created_at and updated_at date in laravel with mongodb

I am having trouble accessing created_at and updated_at properties in a Laravel model using MongoDB. My date format in the database is as follows:
"created_at" : {
"sec" : NumberInt(1475126325),
"usec" : NumberInt(840000)
},
"updated_at" : {
"sec" : NumberInt(1475126325),
"usec" : NumberInt(840000)
},
I get the following result from MongoDB query:
App\Modules\Admin\Models\Segment Object
(
[table:protected] => tbl_segment
[timestamps] => 1
[fillable:protected] => Array
(
[0] => name
[1] => created_at
[2] => updated_at
)
[collection:protected] =>
[primaryKey:protected] => _id
[parentRelation:protected] =>
[connection:protected] =>
[keyType:protected] => int
[perPage:protected] => 15
[incrementing] => 1
[attributes:protected] => Array
(
[_id] => MongoDB\BSON\ObjectID Object
(
[oid] => 57ecbefe15285745ba039871
)
[created_at] => Array
(
[sec] => 1475133182
[usec] => 832000
)
[updated_at] => Array
(
[sec] => 1475133182
[usec] => 832000
)
)
[original:protected] => Array
(
[_id] => MongoDB\BSON\ObjectID Object
(
[oid] => 57ecbefe15285745ba039871
)
[created_at] => Array
(
[sec] => 1475133182
[usec] => 832000
)
[updated_at] => Array
(
[sec] => 1475133182
[usec] => 832000
)
)
[relations:protected] => Array
(
)
[hidden:protected] => Array
(
)
[visible:protected] => Array
(
)
[appends:protected] => Array
(
)
[guarded:protected] => Array
(
[0] => *
)
[dates:protected] => Array
(
)
[dateFormat:protected] =>
[casts:protected] => Array
(
)
[touches:protected] => Array
(
)
[observables:protected] => Array
(
)
[with:protected] => Array
(
)
[morphClass:protected] =>
[exists] => 1
[wasRecentlyCreated] =>
)
When I try to access created_at date, I get the following error:
ErrorException in Model.php line 2983:
preg_match() expects parameter 2 to be string, array given
I had similar issue after updating laravel package (jessengers) for mongodb.You can try - Find following lines
if (preg_match('/^(\d{4})-(\d{1,2})-(\d{1,2})$/', $value)) {
in Model.php found at vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php
and replace it by
if (preg_match('/^(\d{4})-(\d{1,2})-(\d{1,2})$/', $value['sec'])) {
in vendor/nesbot/carbon/src/Carbon/Carbon.php replace createFromFormat() function with -
public static function createFromFormat($format, $time, $tz = null)
{
$time = date('Y-m-d H:i:s' , $time['sec']);
if ($tz !== null) {
$dt = parent::createFromFormat($format, $time, static::safeCreateDateTimeZone($tz));
} else {
$dt = parent::createFromFormat($format, $time);
}
if ($dt instanceof DateTime) {
return static::instance($dt);
}
$errors = static::getLastErrors();
throw new InvalidArgumentException(implode(PHP_EOL, $errors['errors']));
}
Note :- There could be better solution for this , so if anybody else found its alternative then please share.

Put/Get UploadField submitted image from custom Form -> Silverstripe 3.1

I have a small problem programming with the use of UploadField . I have created pages to make a light CMS on the FrontEnd. But I don't know how retrieve this image to the page «Update».
There is the code from the page «Create» :
$uploadField = new UploadField( 'ImageEvenement', 'Image' );
There is the code I tried to get working for the page «Update»
$evenID = Session::get('evenementID');
$evenement = Versioned::get_by_stage('PageCalendrierEvenement', 'Stage')->byID($evenID);
..
$SavedImage = File::get()->byID($evenement->ImageEvenementID)
$uploadField = new UploadField( 'ImageEvenement', 'Image', $SavedImage );
How can I retrieve the submitted image to $SavedImage ? My idea to get the ID from File don't work.
Another method :
$SavedImage = $evenement->ImageEvenement();
If I dump data from $SavedImage I'm viewing :
Image Object
(
[destroyed] =>
[model:protected] => DataModel Object
(
[customDataLists:protected] => Array
(
)
)
[record:protected] => Array
(
[ClassName] => Image
[Created] => 2015-07-15 14:41:24
[LastEdited] => 2015-07-16 15:03:25
[Name] => images.jpg
[Title] => images
[Filename] => assets/Membres/9/calendrier/images.jpg
[ShowInSearch] => 1
[ParentID] => 15
[OwnerID] => 9
[ID] => 22
[RecordClassName] => Image
)
[changed:DataObject:private] => Array
(
)
[original:protected] => Array
(
[ClassName] => Image
[Created] => 2015-07-15 14:41:24
[LastEdited] => 2015-07-16 15:03:25
[Name] => images.jpg
[Title] => images
[Filename] => assets/Membres/9/calendrier/images.jpg
[ShowInSearch] => 1
[ParentID] => 15
[OwnerID] => 9
[ID] => 22
[RecordClassName] => Image
)
[brokenOnDelete:protected] =>
[brokenOnWrite:protected] =>
[components:protected] =>
[unsavedRelations:protected] =>
[sourceQueryParams:protected] =>
[failover:protected] =>
[customisedObject:protected] =>
[objCache:ViewableData:private] => Array
(
)
[class] => Image
[extension_instances:protected] => Array
(
[BetterButtonDataObject] => BetterButtonDataObject Object
(
[owner:protected] =>
[ownerBaseClass:protected] => DataObject
[ownerRefs:Extension:private] => 0
[class] => BetterButtonDataObject
)
[SiteTreeFileExtension] => SiteTreeFileExtension Object
(
[owner:protected] =>
[ownerBaseClass:protected] => File
[ownerRefs:Extension:private] => 0
[class] => SiteTreeFileExtension
)
[Hierarchy] => Hierarchy Object
(
[markedNodes:protected] =>
[markingFilter:protected] =>
[_cache_numChildren:protected] =>
[owner:protected] =>
[ownerBaseClass:protected] => File
[ownerRefs:Extension:private] => 0
[class] => Hierarchy
)
)
[beforeExtendCallbacks:protected] => Array
(
)
[afterExtendCallbacks:protected] => Array
(
)
)
Any idea?
class PageCalendrierEvenement extends Page {
private static $db = array(
"Titre" => "Varchar(50)",
"DateDepart" => "Date",
"DateFin" => "Date",
);
private static $has_one = array(
'Creator' => 'Member',
'ImageEvenement' => 'Image',
);
..
}
Thank you!
has one relations need the "ID" suffix in the name of the relation (as it's saved to db...), e.g.
$uploadField = new UploadField( 'ImageEvenementID', 'Image', $SavedImage );
then it should save automatically.
OR, what i do for a single relation:
$imageField = UploadField::create('ImageEvenement', 'Image');
$imageField->setAllowedFileCategories('image');
$imageField->setAllowedMaxFileNumber(1);
hope that helps.
My code works fine but are not clean and not using SilverStripe function classes. The reason for non working saving images to dataobject, is because that I have not use :
$form->saveInto($evenement)
I would like to thank you Wmk for give me the get method to fill form with values on another post :
$form->loadDataForm($evenement)
Finaly, all works fine now!
Finaly after long time brain searching, I have found the trick! The command to use with UploadField is setValue($value) with fileIDs include with it. My final code is :
$evenement = Versioned::get_by_stage('PageCalendrierEvenement', 'Stage')->byID($evenID);
...
$uploadField = new UploadField( 'ImageEvenement', 'Image' );
$data['ImageID'] = $evenement->ImageEvenement()->ID;
$fileIDs[]=$data['ImageID'];
$uploadField->setValue(array('Files' => $fileIDs));
Thats it!

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.

CodeIgniter, variable declaration

I have a problem with undefined variable. In view/somefolder/somefile.php they echo some variabla (<?php echo $news;?> ) . I tried everything to find where this variable is defined (Find in Path at PHPStorm), but without result. When I put print_r($GLOBALS) to test, I got
[_ci_cached_vars:protected] => Array
(
[unread] => 0
[unans] => 0
[ques_unread] => 0
[is_loged] =>
[level] =>
[avatar] => media/img/avatar.png
[username] =>
[root_cat] => 0
[logErr] =>
[radio_list] => Array
(
)
[entitet] => 1
[current_modul] => infograda
[tree] => <ul></ul>
[category] => stdClass Object
(
[id] => 153
[title] => HRONIKA
[description] =>
[parent_id] => 0
[order] => 52
[module] => infograda
[expanded] => 0
[content_type_id] => 1
)
[module] => infograda
[active] =>
[additionHtml] =>
[news] => Array
(
[0] => stdClass Object
(
[id] => 1574
[content_id] => 1574
[module] => infograda
[order] =>
[title] => Title
[text] => <div class="uvod_holder">
in Codeigniter, a view is loaded from a controller. For example:
Controller:
// this file resides in application\controllers\mycontroller.php
class Mycontroller extends CI_Controller{
function mypage() {
$data = array('news' => 'some news');
$this->load->view('page', $data);// will load views\page.php and pass the $data array
}
}
View
<!--this file resides in application\views\page.php -->
<html>
<head></head>
<body><?= $news; ?></body>
</html>
To make this work, your URL will say http://localhost/index.php/mycontroller/mypage (if you're working locally)
Your variable is being set in the controller that loads that view.

Resources