Symfony2: Call to a member function toArray() on a non-object - php

Hy,
I've a short question about a weird error message I get on my Symfony 2 project.
I've an entity class User which retrieves its roles via Doctrine. This works perfectly! But...
I want let the User implement EquatableInterface, so I've added the User::isEqualTo method. This is where my error occurs. This line, especially $this->getRoles()is causing the error:
Symfony2: Call to a member function toArray() on a non-object
But the same toArray function usage inside User::getRoles() works great on the rest of the project. So I don't get what's wrong here.
Can somebody help me with it? Any help appreciated!
Update 1
Looking into the logs and using your current help, here are some insights:
$thisin getRoles always returns the entity user class, so nothing special there, but
After each isEqualTocall, $this->rolesreturns null, after that it doesn't.
Update 2
Here are my further insights:
I've added Konstantin's is_nullcheck, but it doesn't solve the actual problem.
As I could see in the logs during logging in, refreshUser is called and everything is perfect. Roles are found. After refreshUser isEqualTois fired and suddenly $this->rolesbecomes null and get_class($this->roles)returns user entity class (?!?!?) in comparison to Doctrine\\ORM\\PersistentCollection.
When I add the roles to the user's (un)serialize methods everything seems to be fine inside this isEqualTo method. He finally is grabbing the roles and I can add my logic to it. Fine! But afterwards Symfony is throwing erros like this or that. In my pov it has something to do with the serialization.
After some readings I've added serialization to the role entity because this seems the standard way to go. Serializing the user and the roles on their own, not (un)serializing the roles inside the user class. But as soon as I'm removing the roles from the user's serializing methods the old problem occurs again and again concerning $this->roles is always null when isEqualTo is fired. Everytime before and after everything's great, except this method call.
I haven't any clue what's exactly going wrong here.
Any idea?

Most likely this is caused by $this->roles being not populated at the moment of getRoles() call. It's hard to say what exactly is causing it without going through your other code. An easy solution would be to add a check to your getRoles() method at line 138:
if ($this->roles === null) {
return null;
}
But I'm not sure that's what you want to do, you probably want to figure out why roles are actually empty at that moment.

Related

Laravel Eloquent update cannot see columns that needs to be updated

Hello guys, I created a "promos" table and now, I am working on the CRUD functionalities of this module. The "create" functionality is done and I encountered no problems. My only problem is this when I am updating my model and it is very weird.
It seems that $this->model->where('id', $id)->first() cannot see and retrieve the list of columns. Here is the screenshot.
I already tried composer dump-autoload and php artisan clear-compiled hoping the problem will fix itself.
For additional reference, here is my schema, model and code:
Other notes: $this->model points to the Promo model
EDIT:
I did not display the controllers specifically the update method as stated by #OmarTarek. Our company is using RepositoryInterface Pattern. Instead of the normal View=>Controller=>Model when saving data to the database, our workflow is like this View=>Controller=>Repository=>Model
In my controller, my code is
While in my repository, my code is like this:
As you can see, I am inheriting the BaseRepository.php because it has all the necessary functions/methods for create, update and delete.
It is the BaseRepository
I highlighted the code that is giving the error.
EDIT II:
I already implemented the change suggested by #PaladiN. The error still displays and the update method still don't work.
You can remove the first() since the id is a primary key. Also you're calling the update statement again on updateData() method, you should remove that.
$this->model->where($key, $value)->update($data);
Also when you either define $fillable or $guarded, not both. When you define $guarded with an empty array, all the fields become fillable by default. Another thing would be to check if the model created in the constructor using make() is a valid model instance before proceeding.
sorry for the late update. I just fixed this error but I still don't know how this error happened. It seems that a mutator from our BaseModel.php interferes with the updating of data.
I tried overriding the mutator in my Promo.php model to make the update method work and the error no longer shows.
I still don't know what caused the error but I am eager to deliver this module first to our clients so I will investigate how this scenario happened next time.
Thanks guys.

Using polymorphic relationships in Eloquent to extend model

I am quite new to Slim, still trying to learn it and decided to redo an old app I'd made. I am trying to use Eloquent but have quickly gotten lost doing what I wouldn't think is very complicated.
The app I had was even too complicated to learn on, so I backtracked to this tutorial here, as this is more or less what I am trying to do, use models extending one other class, to see if I can even get this working: http://www.richardbagshaw.co.uk/laravel-user-types-and-polymorphic-relationships/ It's just a user type extension.
I cannot. This is a tutorial for Laravel obviously, so I know it will be a bit different. I have recreated the database (minus some of the extraneous stuff like username and password) and populated it sufficiently. I have copied the code for the User, Freelancer and Employee classes, modifying only the User class removing the extra methods which don't seem to be required for this (I think) as below.
namespace eloquent\eloquent;
class User extends Eloquent implements {
protected $table = 'users';
public function userable()
{
return $this->morphTo();
}
}
If I do this:
$user = $app->user->find(1)->firstName;
echo $user
It works as expected.
This does not:
$user = $app->user->find(1);
echo $user->userable->dayrate;
It gives me this:
Fatal error: Class 'Employee' not found in D:\Apache24\htdocs\eloquent\vendor\illuminate\database\Eloquent\Model.php on line 900
It does however correctly identify whether it's looking for an employee or a freelancer, which I assume is coming from the DB column userable_type.
Question is really how should I be accessing the fields of the subclass? Am I doing it totally wrong, or is there a better way?
I eventually came back to this question, and was able to solve it, just in case anyone else is having a similar problem.
The problem was that it was looking for the exact string in the Database as the usertype, in this case Employee. What it really needed, was to look for the whole string including the namespace. By adding the entire namespace into the database entry as userable_type (ie eloquent\eloquent\Employee) it then picks it up and can find the model...
I looked into options in Eloquent, like MorphClass but that does not appear to do what I need.
I haven't actually implemented this into a project I'm working on yet, but I imagine I'll probably either leave the whole string in there because I'm lazy and it's not a mission-critical, time sensitive app, or try to do something with middleware or ??. Anyways, hope that helps someone else.

Cannot load custom controller in Opencart 2

I have created a custom controller in "admin/controller/mycustomcontroller/mycustomcontroller.php" to handle some AJAX requests among other things for my back-end modules. This custom controller contains an add() method that I intend to use.
Situation:
I gave read/write permissions to the Administrator user group.
Calling the add method of my custom controller through AJAX works fine.
Same as accessing it directly through url route=mycustomcontroller/mycustomcontroller.php/add
Problem:
I cannot load the controller using:
$this->load->controller('mycustomcontroller/mycustomcontroller/add');
I tried to load it in the admin/controller/catalog/product.php file and inside my model file but it returns nothing (no result, no error, nothing).
I am new to Opencart and I don't know what's the problem, in the worst case scenario I will just cURL the controller file but that doesn't feel right.
After many tests I finally found the problem, and it's quite silly.
Let's say you want your controller to return an encoded json string so that you can use it in your javascript, you could write (by habit):
$this->response->setOutput(json_encode($result));
Big mistake! Setting the output through this function won't be taken into account when the load->controller() method is called, so even though your AJAX/JS will still work fine, nothing else will. instead use:
return json_encode($result)
The fact that no one had stumbled upon this issue before astonishes me, I am either stupid or missing something important in OC documentation.

Difference between Woodling::saved and Woodling::retrieve

I am writing my unit tests with phpunit to Laravel application. I am using Eloquent and Woodling library. I want to test many to many relationship.
I have Users table and Friends table. Everything worked, when I tested it manually. I am able to add friends. I wanted to test this functionality.
I created blueprints and I call them with saved method like this.
$user = Woodling::saved('LonelyUser');
$user2 = Woodling::saved('LonelyUser2');
$users = User::all()->toArray();
var_dump($users);
$user->addFriend($user2);
I got a database constraint error in the last line, because the users were not persisted to database (I know that, because they are not in var_dump output).
If Woodling::saved does not persist to database, than what does it do? The docs say, that it calls save method on model. save method should persist the model to database.
What is the saved method purpose and how is it different than retrieve?
Woodling::saved persists to database correctly, but if something goes wrong during saving, it doesn't show any errors. In my case save method was actually Ardent::save, which does some validations. This validations did not pass and Model::save was never called.

Laravel: Know What to Implement in model

I am just about three days old in laravel, yesterday I tried creating an authentications system using eloquent, so without looking I deleted the default User model, and then I tried creating my own from what I had read from the documentation. After setting up every thing as I had studied and understood, I tried running my app, but whenever I enter the correct username and password I get this error
Argument 1 passed to Illuminate\Auth\EloquentUserProvider::validateCredentials()
must be an instance of Illuminate\Auth\UserInterface, instance of User given, called in dir
I did not know what the EloquentUserProvider was or where it was even coming from. My original model looked like this
class User extends Eloquent {}
I battled with this error for the whole day (no exaggeration), But today I found out from this SO Can't authenticate user in laravel that it was because I had not implemented some interface, so they linked me to https://github.com/laravel/laravel/blob/master/app/models/User.php where I copied the default model I initially deleted.
I used the documentation almost through out my learning process, and no where in the documention for authentication and for eloquent did they mention that we are suppose to implement these interface for us to be able to use Auth::attempt() method, my question now is how then do we (newbies) know what to implement and what not to implement, or what any of these interfaces even do.
This is simple. It's a laravel's requirement. The User model is generated by default for you. If you do not need to implement the interface's methods, just add them empty in your User class.
And of course, in your case, what to extend or implement will be shown as errors on startup. Reading them carefully can give you all the asnwers.
Also, if you want to use different User Authentication features, or extend the existing ones, you can look some info here in the docs

Categories