How can I get access to object properties (arraycollection)? - php

This is my object products:
array:1 [▼
0 => Products {#8662 ▼
-id: 5
-name: "lion"
-unique_id: "7726d59574"
-productgroup: PersistentCollection {#8763 ▼
-snapshot: array:2 [ …2]
-owner: Products {#8662}
-association: array:20 [ …20]
-em: EntityManager {#4326 …11}
-backRefFieldName: null
-typeClass: ClassMetadata {#8294 …}
-isDirty: false
#collection: ArrayCollection {#8666 ▼
-elements: array:2 [▼
0 => Productgroup {#8765 ▼
-id: 5
-name: "Mammals"
-unique_id: "12102400f9"
}
1 => Productgroup {#8769 ▼
-id: 7
-name: "Fish"
-unique_id: "f0fbfa5c19"
}
]
}
#initialized: true
}
}
]
When I create json file like this...
$result = $serializer->serialize($products, 'json');
...I get this result:
[{"id":5,"uniqueId":"7726d59574","name":"lion","productgroup":[{"id":5,"uniqueId":"12102400f9","name":"Mammals"},{"id":7,"uniqueId":"f0fbfa5c19","name":"Fish"}]}]
But the result that I need is only productgroup. So this is what I try to achieve:
[{"id":5,"uniqueId":"12102400f9","name":"Mammals"},{"id":7,"uniqueId":"f0fbfa5c19","name":"Fish"}]
This was my first approach:
$data = $products->productgroup;
$result = $serializer->serialize($data, 'json');
But I got the error message:
Notice: Trying to get property 'productgroup' of non-object
I thought, oh ok, this means, products is not an object, so I tried this:
foreach ($products as $product) {
$data = $product['productgroup'];
}
$result = $serializer->serialize($data, 'json');
But now I get the error:
Cannot use object of type App\Entity\Products as array

try to use something like this:
foreach ($products as $product) {
$data = $product->getProductGroup();
}
Method getProductGroup must exists into your entity, if not you can have something similar I think.

Related

Array_merge in laravel

I have data I return them into collection but it does not return as i wish and i need help to fix it.
output
array:11 [▼
0 => Collection {#2762 ▼
#items: array:3 [▼
0 => Product {#2758 ▶}
1 => Product {#2759 ▶}
2 => Product {#2760 ▶}
]
}
1 => Collection {#2792 ▼
#items: []
}
2 => Collection {#2948 ▼
#items: []
}
3 => Collection {#3102 ▼
#items: []
}
4 => Collection {#3216 ▼
#items: []
}
5 => Collection {#2886 ▼
#items: array:10 [▶]
}
6 => Collection {#2920 ▼
#items: array:3 [▶]
}
7 => Collection {#3046 ▼
#items: array:12 [▶]
}
8 => Collection {#3074 ▼
#items: []
}
9 => Collection {#3188 ▼
#items: array:7 [▶]
}
10 => Collection {#3288 ▼
#items: []
}
]
Code
$category = Category::where('slug','=',$catslug)->with('childs', 'parent')->first();
$pp1[] = Product::where('category_id',$category->id)->get();
foreach($category->childs as $first){
$pp2[] = Product::where('category_id',$first->id)->get();
if(count($first->childs)> 0){
foreach($first->childs as $second){
$pp3[] = Product::where('category_id',$second->id)->get();
}
}
}
$products = array_merge($pp1,$pp2,$pp3);
dd($products);
What it should return
It should return all products from all arrays in 1 array only and not categorized by Collection {#2792 ▼ I need to get only collections with items and not the ones that are empty.
Any idea?
update
I've also tried this:
$pp1 = [];
$pp2 = [];
$pp3 = [];
$pp1 = Product::where('category_id',$category->id)->get();
foreach($category->childs as $first){
$pp2 = Product::where('category_id',$first->id)->get();
if(count($first->childs)> 0){
foreach($first->childs as $second){
$pp3 = Product::where('category_id',$second->id)->get();
}
}
}
it returns:
array_merge(): Argument #1 is not an array
You can get all products of the category, of its children and of its grand-children as,
$category = Category::where('slug','=',$catslug)
->with([
'products',
'childs.products',
'childs.childs.products',
'parent'
])
->first()
->toArray();
$products = array_merge([
data_get($category, 'products'),
array_collapse(data_get($category, 'childs.*.products')),
array_collapse(data_get($category, 'childs.*.childs.*.products'))
]);
Fiddle : https://implode.io/ebXrD8

How can I overwrite a protected property of an object?

This is the result of dd($followers):
LengthAwarePaginator {#401 ▼
#total: 144
#lastPage: 8
#items: Collection {#402 ▼
#items: array:18 [▶]
}
#perPage: 20
#currentPage: 1
#path: "http://myurl.com/SocialCenter/public/twitterprofile/JZarif"
#query: []
#fragment: null
#pageName: "page"
}
Now I want to know, how can I overwrite #total? I mean I want to reinitialize it to 18. So this is the expected result:
LengthAwarePaginator {#401 ▼
#total: 18
#lastPage: 8
#items: Collection {#402 ▼
#items: array:18 [▶]
}
#perPage: 20
#currentPage: 1
#path: "http://myurl.com/SocialCenter/public/twitterprofile/JZarif"
#query: []
#fragment: null
#pageName: "page"
}
Is doing that possible?
Noted that none of these work:
$followers->total = 18;
$followers['total'] = 18;
You could use reflection:
$reflection = new \ReflectionObject($followers);
$property = $reflection->getProperty('total');
$property->setAccessible(true);
$property->setValue(
$followers,
18
);
For reference, see:
http://php.net/manual/en/class.reflectionobject.php
http://php.net/manual/en/class.reflectionproperty.php
You should make a getter and setter function.
But you can use PHP-Reflections. Like this example:
<?php
class LengthAwarePaginator
{
private $total = true;
}
$class = new ReflectionClass("LengthAwarePaginator");
$total = $class->getProperty('total');
$total->setAccessible(true);
$total->setValue(18);

Saving request to database

I want to save a request from my laravel 5.2 app a form into my database:
When I submit the request with the word testdy I get an exception:
FatalThrowableError in KeywordController.php line 49: Class
'App\Keyword' not found
Line 49 in my controller is when I want to built my model: $keyword = new Keyword($request);
Below you can find the code of the KeywordController:
<?php
namespace App\Http\Controllers;
use App\Keyword;
use App\Http\Requests\KeywordRequest;
use Response;
use Sentinel;
class KeywordController extends JoshController
{
public function __construct()
{
parent::__construct();
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
// Grab all the Keywords
// $Keywords = Keyword::all();
// Show the page
return View('admin.keyword.index'); //, compact('Keywords'));
}
public function create()
{
// $Keywordcategory = KeywordCategory::lists('title', 'id');
return view('admin.keyword.create'); //, compact('Keywordcategory'));
}
public function store(KeywordRequest $request)
{
//dd($request);
$keyword = new Keyword($request); //line 49 of my controller
$keyword->user_id = Sentinel::getUser()->id;
$keyword->save();
if ($keyword->id) {
return redirect('admin/keyword')->with('success', trans('Keyword/message.success.create'));
} else {
return Redirect::route('admin/keyword')->withInput()->with('error', trans('Keyword/message.error.create'));
}
}
public function show(Keyword $keyword)
{
$comments = Keyword::all();
return view('admin.keyword.show', compact('Keyword', 'comments', 'tags'));
}
public function edit(Keyword $keyword)
{
$Keywordcategory = KeywordCategory::lists('title', 'id');
return view('admin.keyword.edit', compact('Keyword', 'Keywordcategory'));
}
public function update(KeywordRequest $request, Keyword $Keyword)
{
if ($request->hasFile('image')) {
$file = $request->file('image');
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension() ?: 'png';
$folderName = '/uploads/Keyword/';
$picture = str_random(10).'.'.$extension;
$Keyword->image = $picture;
}
if ($request->hasFile('image')) {
$destinationPath = public_path().$folderName;
$request->file('image')->move($destinationPath, $picture);
}
$Keyword->retag($request['tags']);
if ($Keyword->update($request->except('image', '_method', 'tags'))) {
return redirect('admin/keyword')->with('success', trans('Keyword/message.success.update'));
} else {
return Redirect::route('admin/keyword')->withInput()->with('error', trans('Keyword/message.error.update'));
}
}
public function getModalDelete(Keyword $Keyword)
{
$model = 'Keyword';
$confirm_route = $error = null;
try {
$confirm_route = route('delete/Keyword', ['id' => $Keyword->id]);
return View('admin/layouts/modal_confirmation', compact('error', 'model', 'confirm_route'));
} catch (GroupNotFoundException $e) {
$error = trans('Keyword/message.error.delete', compact('id'));
return View('admin/layouts/modal_confirmation', compact('error', 'model', 'confirm_route'));
}
}
public function destroy(Keyword $Keyword)
{
if ($Keyword->delete()) {
return redirect('admin/keyword')->with('success', trans('Keyword/message.success.delete'));
} else {
return Redirect::route('admin/keyword')->withInput()->with('error', trans('Keyword/message.error.delete'));
}
}
}
My request, see the dd($request); looks like the following:
KeywordRequest {#323 ▼
#container: Application {#3 ▶}
#redirector: Redirector {#330 ▼
#generator: UrlGenerator {#114 ▼
#routes: RouteCollection {#26 ▶}
#request: Request {#40 ▶}
#forcedRoot: null
#forceSchema: null
#cachedRoot: null
#cachedSchema: null
#rootNamespace: "App\Http\Controllers"
#sessionResolver: Closure {#115 ▶}
#dontEncode: array:14 [▶]
}
#session: Store {#264 ▼
#id: "6db1ef2a6ede612fa681e299c7731866afce7b34"
#name: "laravel_session"
#attributes: array:4 [▼
"_token" => "HbguKauEYhU00n9YcCvw8lloKWbd51I6FOhHRORB"
"_previous" => array:1 [▶]
"flash" => array:2 [▶]
"cartalyst_sentinel" => "5jqJ2R6MTFm4DkOefwhknOD3WY4Jaa0T"
]
#bags: []
#metaBag: MetadataBag {#255 ▼
-name: "__metadata"
-storageKey: "_sf2_meta"
#meta: &120 array:3 [▼
"u" => 1492269234
"c" => 1492243279
"l" => "0"
]
-lastUsed: 1492269215
-updateThreshold: 0
}
#bagData: array:1 [▶]
#handler: FileSessionHandler {#265 ▼
#files: Filesystem {#117}
#path: "/home/ubuntu/workspace/storage/framework/sessions"
#minutes: 120
}
#started: true
}
}
#redirect: null
#redirectRoute: null
#redirectAction: null
#errorBag: "default"
#dontFlash: array:2 [▼
0 => "password"
1 => "password_confirmation"
]
#json: null
#convertedFiles: []
#userResolver: Closure {#232 ▼
class: "Cartalyst\Sentinel\Laravel\SentinelServiceProvider"
this: SentinelServiceProvider {#77 …}
use: {▼
$app: Application {#3}
}
file: "/home/ubuntu/workspace/vendor/cartalyst/sentinel/src/Laravel/SentinelServiceProvider.php"
line: "425 to 427"
}
#routeResolver: Closure {#233 ▼
class: "Illuminate\Routing\Router"
this: Router {#24 …}
use: {▼
$route: Route {#149 ▼
#uri: "admin/keyword/create"
#methods: array:1 [▶]
#action: array:6 [▶]
#defaults: []
#wheres: array:1 [▶]
#parameters: []
#parameterNames: []
#compiled: CompiledRoute {#239 ▶}
#router: Router {#24 …}
#container: Application {#3}
}
}
file: "/home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Routing/Router.php"
line: "693 to 695"
}
+attributes: ParameterBag {#325 ▼
#parameters: []
}
+request: ParameterBag {#322 ▼
#parameters: array:2 [▼
"_token" => "HbguKauEYhU00n9YcCvw8lloKWbd51I6FOhHRORB"
"keyword" => "tesdy"
]
}
+query: ParameterBag {#324 ▼
#parameters: []
}
+server: ServerBag {#328 ▼
#parameters: array:42 [▶]
}
+files: FileBag {#327 ▼
#parameters: []
}
+cookies: ParameterBag {#326 ▼
#parameters: array:2 [▼
"XSRF-TOKEN" => "HbguKauEYhU00n9YcCvw8lloKWbd51I6FOhHRORB"
"laravel_session" => "6db1ef2a6ede612fa681e299c7731866afce7b34"
]
}
+headers: HeaderBag {#329 ▼
#headers: array:16 [▼
"host" => array:1 [▶]
"content-length" => array:1 [▶]
"cache-control" => array:1 [▶]
"origin" => array:1 [▶]
"upgrade-insecure-requests" => array:1 [▶]
"user-agent" => array:1 [▶]
"content-type" => array:1 [▶]
"accept" => array:1 [▶]
"referer" => array:1 [▶]
"accept-encoding" => array:1 [▶]
"accept-language" => array:1 [▶]
"cookie" => array:1 [▶]
"x-forwarded-proto" => array:1 [▶]
"x-forwarded-port" => array:1 [▶]
"x-forwarded-for" => array:1 [▶]
"connection" => array:1 [▶]
]
#cacheControl: array:1 [▼
"max-age" => "0"
]
}
#content: ""
#languages: null
#charsets: null
#encodings: null
#acceptableContentTypes: null
#pathInfo: null
#requestUri: null
#baseUrl: null
#basePath: null
#method: "POST"
#format: null
#session: Store {#264 ▶}
#locale: null
#defaultLocale: "en"
}
The "keyword" => "tesdy" parameter has the same name in the database.
Any suggestions why $keyword = new Keyword($request); throws an exception?
I appreciate your replies!
Update
My app/Keyword.php file looks like the following:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Keywords extends Model
{
protected $table = 'keywords';
protected $guarded = ['id'];
}
Model name should be Keyword, change it and this will solve the problem:
class Keyword extends Model
Just change the class name to Keyword from Keywords in your app/Keyword.php. The class name should equals to its file name.

Doctrine object incomplete when no session cookie, why?

I've encountered a silly problem this morning and I struggle to find a decent solution. Maybe you can tip me...
I've this simple function in a entity repository, with a simple query:
public function findAvailabilityByDr($delivery_round_id) {
$qb = $this->_em->createQueryBuilder()
->select('partial dro.{id},
partial drp.{id, maxDeliveries, countDeliveries},
partial zdd.{id, day},
partial rer.{id, maxOrders, countOrders}')
->from($this->_entityName, 'dro')
->leftJoin('dro.parts', 'drp')
->leftJoin('drp.day', 'zdd')
->leftJoin('drp.relayRounds', 'rer')
->where('dro.id = :delivery_round_id')
->setParameters(array(
'delivery_round_id' => $delivery_round_id,
));
dump($qb->getQuery()->getOneOrNullResult());
die();
}
At the first load (with no session cookie created), I got an incomplete result:
DeliveryRound {#342 ▼
-id: 117
-endOfOrdersDate: DateTime {#346 ▶}
-parts: PersistentCollection {#428 ▼
-snapshot: array:2 [ …2]
-owner: DeliveryRound {#342}
-association: array:15 [ …15]
-em: EntityManager {#695 …11}
-backRefFieldName: "deliveryRound"
-typeClass: ClassMetadata {#373 …}
-isDirty: false
#collection: ArrayCollection {#412 ▼
-elements: array:2 [▼
0 => DeliveryRoundPart {#425 ▼
-id: 134
-deliveryDate: DateTime {#347 ▶}
-deliveryHourStart: null
-deliveryHourEnd: null
-maxDeliveries: null <------ HERE !!!!!!!!!!!
-countDeliveries: null
-deliveryRound: DeliveryRound {#342}
-day: ZoneDeliveryDay {#1302 ▶}
-ordersCustomers: PersistentCollection {#358 ▶}
-ordersProviders: PersistentCollection {#410 ▶}
-relayRounds: PersistentCollection {#637 ▶}
-roadSheetOptimizationData: null
}
1 => DeliveryRoundPart {#1444 ▶}
]
}
#initialized: true
}
-ordersProvidersGenDate: null
-roadSheetPath: null
-roadSheetGenDate: null
-preparationSheetPath: null
-preparationSheetGenDate: null
-deliveryMailNotificationsSendingDate: null
-deliveryNotificationsSendingDate: null
#translations: PersistentCollection {#420 ▶}
#newTranslations: null
#currentLocale: "fr"
#defaultLocale: "fr"
}
And at the second call (refresh), the session cookie is created and the result is correct (maxDeliveries: 30 is a correct value):
DeliveryRound {#1657 ▼
-id: 117
-endOfOrdersDate: null
-parts: PersistentCollection {#1794 ▼
-snapshot: array:2 [ …2]
-owner: DeliveryRound {#1657}
-association: array:15 [ …15]
-em: EntityManager {#695 …11}
-backRefFieldName: "deliveryRound"
-typeClass: ClassMetadata {#1673 …}
-isDirty: false
#collection: ArrayCollection {#1795 ▼
-elements: array:2 [▼
0 => DeliveryRoundPart {#1747 ▼
-id: 134
-deliveryDate: null
-deliveryHourStart: null
-deliveryHourEnd: null
-maxDeliveries: 30 <------ HERE !!!!!!!!!!!
-countDeliveries: 0
-deliveryRound: DeliveryRound {#1657}
-day: ZoneDeliveryDay {#2063 ▶}
-ordersCustomers: PersistentCollection {#1904 ▶}
-ordersProviders: PersistentCollection {#1896 ▶}
-relayRounds: PersistentCollection {#2187 ▶}
-roadSheetOptimizationData: null
}
1 => DeliveryRoundPart {#2188 ▶}
]
}
#initialized: true
}
-ordersProvidersGenDate: null
-roadSheetPath: null
-roadSheetGenDate: null
-preparationSheetPath: null
-preparationSheetGenDate: null
-deliveryMailNotificationsSendingDate: null
-deliveryNotificationsSendingDate: null
#translations: PersistentCollection {#1799 ▶}
#newTranslations: null
#currentLocale: "fr"
#defaultLocale: "fr"
}
And when I use $qb->getQuery()->getArrayResult()
the results are correct in both cases.
WTF ? Is it bug ?
Thanks for your help !
EDIT
If I reduce it to its simplest expression, with no partial and a call from a controller, the bug is still there...
Repository:
public function findAvailabilityByDr($delivery_round_id) {
$qb = $this->_em->createQueryBuilder()
->select('dro,
drp')
->from($this->_entityName, 'dro')
->leftJoin('dro.parts', 'drp')
->where('dro.id = :delivery_round_id')
->setParameters(array(
'delivery_round_id' => $delivery_round_id,
));
return $qb->getQuery()->getOneOrNullResult();
}
Controller:
class StructureController extends BasePublicCommonController
{
public function indexAction()
{
$delivery_round = $this->getDoctrine()->getManager()->getRepository('ProxymartDeliveryBundle:DeliveryRound')->findAvailabilityByDr(117);
dump($delivery_round);
die();
}
}
This is for things like this I hate programming sometimes :)
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/partial-objects.html
I don't know about the cookie, but I know for arrayResult():
The partial object problem in general does not apply to methods or queries where you do not retrieve the query result as objects. Examples are: Query#getArrayResult() [...]

How to get a value from a Array symfony2.8

Hi everyone i'm looking for a way to get a value in a variable but i'm stuck with an array like
$prixArrayArticle = $article->getArticlePlateforme()->getValues();
dump($prixArrayArticle);
gives me
ReassortController.php on line 1149:
array:1 [▼
0 => ArticlePlateforme {#1469 ▼
-article: Article {#1321 ▶}
-plateforme: Plateforme {#1051 ▶}
-codeProduitGv: "365717 "
-fournisseurCommun: FournisseurAchatsAdherents {#1445 ▶}
-referenceFournisseur: "100050 "
-minimumCommande: 1
-colisage: 12
-qtePalette: 12
-decolisable: true
-stock: 182
-dateCreation: DateTime {#1326 ▶}
-present: true
-articleSubstitution: null
-prix: PersistentCollection {#1430 ▼
-snapshot: array:1 [ …1]
-owner: ArticlePlateforme {#1469}
-association: array:19 [ …19]
-em: EntityManager {#137 …11}
-backRefFieldName: null
-typeClass: ClassMetadata {#1261 …}
-isDirty: false
#collection: ArrayCollection {#1439 ▼
-elements: array:1 [▼
0 => Prix {#1412 ▼
-id: 4175988
-dateDebut: DateTime {#1325 ▶}
-dateFin: DateTime {#1324 ▶}
-prixNet: "4.970"
-prixVenteConseille: null
-quantiteMinimum: null
-type: "permanent"
-numeroPromo: null
-offreComplementaire: false
-minimumCommande: 0
-colisage: 0
-invisible: null
-present: true
}
]
}
#initialized: true
}
-prixPromo: PersistentCollection {#1399 ▶}
}
]
and this
$article = $requeteArticle->getQuery()->getSingleResult();
give me this
ReassortController.php on line 1129:
Article {#769 ▼
-id: 1000940
-nom: "FILM DE PAILLAGE FRAISES FRESAFILM 1M40X10M"
-nomCourt: "FILM PAILLAGE FRAISES 1M40X10M"
-gamme: 5
-ecoContribution: "0.00"
-ecoMobilier: "0.00"
-quantiteAchat: "1.00"
-nombreUvParUa: "1.00"
-prixVenteConseille: "9.50"
-present: true
-tauxTva: TauxTva {#908 ▶}
-marque: null
-articleGencod: PersistentCollection {#1007 ▶}
-sousFamille: SousFamille {#635 ▶}
-articlePlateforme: PersistentCollection {#960 ▶}
-uniteAchat: UniteConditionnement {#833 ▶}
-uniteVente: UniteConditionnement {#833 ▶}
}
how can i get the name value for example in a variable because the array only have one index and i really don't know how to get a value with this array
Assuming that the properties are protected and that you have getters for them in your ArticlePlateforme and Article class, you should be able to get them like that:
$articleName = $prixArrayArticle[0]->getArticle()->getNom();
Otherwise, if the properties are public, you could simply get them like:
$articleName = $prixArrayArticle[0]->article->nom;

Categories