In a Laravel 5 app, I have a "User" model and a "Permission" model, both with corresponding tables, that have a many-to-many relationship. There is a pivot table as well: "permission_user".
The User model contains the following method:
public function permissions()
{
return $this->belongsToMany('App\Permission');
}
And the Permission model contains the following method:
public function users()
{
return $this->belongsToMany('App\User');
}
I have been accessing user permissions in custom middleware with the following code, and it's been working splendidly until today.
$permissions = \Auth::user()->permissions()->get();
All of a sudden, this is breaking. I get the following error:
ErrorException in BelongsToMany.php line 177: Argument 1 passed to
Illuminate\Database\Eloquent\Relations\BelongsToMany::hydratePivotRelation()
must be of the type array, object given, called in
/Server/sites/app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php
on line 158 and defined
Really not sure what's going on here. In an attempt to follow the docs more closely, I also tried this:
foreach (\Auth::user()->permissions as $permission)
{
// do something with $permission
}
But I get the same thing (the stack trace shows that the lines shown here are the last ones executed before heading into the Laravel source). I did update Laravel with Composer around the time this happened, but thought it unlikely that something in Laravel source has caused the problem. Can anyone see what I might be doing wrong here, and how I can fix it?
Sit tight, I believe this might actually just a current bug with Laravel 5 (which is still technically in alpha, so breaking changes are to be expected).
Taylor Otwell (the creator of Laravel) tweeted this earlier:
https://twitter.com/taylorotwell/status/553262692426059776
However, it looks like several parts of Laravel 5 core still need to be updated to be compatible with this change.
If you need your app to work right now, just change this in your composer.json file:
"laravel/framework": "~5.0",
to this:
"laravel/framework": "dev-master#9b108d85ce19300dfdd479fa4e05d9ea6e4e3abc",
And then run a composer update. This will pull in yesterdays version of Laravel 5, which was working.
Don't forget to change it back though once this is fixed!
Related
in my system:
a lead belongstomany salespeople
a manager belongstomany salespeople
i am trying to check if a lead has a manager through the salespeople. this is for a policy so i can make sure a manager can see the leads of their salespeople.
something like this:
$lead->salespeople->contains($manager->salespeople)
is there a collection method that will allow me to do this? i've also tried stuff like this which isn't working either:
$lead->salespeople->contains('id', $manager->salespeople->pluck('id')->toArray())
edit, i think i got it. does this look correct?:
$lead->salespeople->intersect($manager->salespeople)->count() > 0
Ended up solving this problem with this package: https://github.com/staudenmeir/eloquent-has-many-deep
Here's my relationship method now:
public function managers()
{
return $this->hasManyDeepFromRelations($this->salespeople(), (new User)->setAlias('salesperson')->managers());
}
I'm using spatie/laravel-menu and spatie/laravel-persmissions in my laravel project.
I have created a permission, assigned it to a role, and assigned the role to my user. This works fine.
Then I have generated a menu the middleware way using a macro like so:
\Menu::macro('main', function () use ($request) {
return \Menu::new()
->withoutWrapperTag()
->withoutParentTag()
->setActiveClassOnLink()
->route('preparation', 'Anstehende Termine')
->route('postprocessing', 'Nachbereitung')
->routeIfCan('administrate', 'protocols', 'Protokolle')
->addItemClass('nav-link')
->setActive($request->url());
});
In my application I have two User models with different connections:
App\User; using connection_a with database db_a and
App\DirectoryA\User; using connection_b with database db_b
In the auth config the first one is defined, and using Auth::user()->can('administrate') works fine, even in the Middleware that defines the menu.
Since I have added the menu item via routeIfCan, I'm getting an error. It tells
Base table or view not found: 1146 Table 'db_b.permissions' doesn't exist (SQL: select permissions.*, model_has_permissions.model_id as pivot_model_id, model_has_permissions.permission_id as pivot_permission_id, model_has_permissions.model_type as pivot_model_type from permissions inner join model_has_permissions on permissions.id = model_has_permissions.permission_id where model_has_permissions.model_id = 1 and model_has_permissions.model_type = App\User)
What is going wrong here? It should use the App\User model. Placing a dd() at the point the framework throws the exception shows me the correct connection...
Please help.
this mean table permissions not exist on your database maybe you forgot to run php artisan migrate after install laravel-permission?
A member of spatie helped to solve the problem:
Under the hood, routeIfCan calls app(Gate::class)->allows($ability, $ablityArguments). I assume Gate behaves slightly different than Auth::user() when it comes to multiple guards.
I don't see much room in routeIfCan to add an additional $guard or $connection argument, so I suggest you use $menu->addIf(Auth::user()->can('administrate'), ...) instead.
I'm upgrading a big project form Yii1 to Yii2. I'm having some problems regarding to ORM.
I have several relation declared in the following fashion(basically a copy-paste from the guidebook):
class Order extends \yii\db\ActiveRecord {
/* other code */
public function getAffiliate()
{
return $this->hasOne(Affiliate::className(), ['id_affiliate' => 'affiliate_id']);
}
Whenever I try to echo or w/e $order->affiliate->name; I get the following error:
yii\base\ErrorException: Trying to get property of non-object
I've got no experience with Yii1 what so ever. Something weird about this project is the database. All tables start with yii_tablename and id's are: id_tablename. Was that normal for Yii1 and could this be causing the issue above?
Edit: When I execute the function like so: $order->getAffilate() it returns an ActiveQuery WITHOUT the data from the affiliate.
When I execute the following:
$order->getBillingAddress()->one();
I get a weird error:
Getting unknown property: app\models\Order::billing
return $this->hasOne(Affiliate::className(), ['id_affiliate' => 'affiliate_id']);
It's mean that when you call $order->affiliate yii2 will find in Affiliate table on id_affiliate field current Order affiliate_id value and selected one value.
Check that you have right field names and database have right data.
When you call $order->affiliate you will get Affiliate object. But if you call $order->getAffiliate() you will get ActiveQuery object.
I found a solution. One which I don't really like though, but it does the job. Was reading this thread: link.
Kartik V
The problem is clearly in uniqueness in naming your relation and your model attribute. In your User model, you have an attribute named role and you also have a relation getter named getRole.
So I changed the name of the getter like so:
public function getOrderAffiliate()
{
return $this->hasOne(Affiliate::className(), ['id_affiliate' => 'affiliate_id']);
}
And that fixed the issue. Never had this issue before and wonder why this happened though.
In this gist, I have 3 controllers defined. I want to establish a parent/child relationship between the cah_annotation and the standard_proposal resource. I cannot find the reason for this error:
$ ./app/console debug:router
[Symfony\Component\Config\Exception\FileLoaderLoadException]
Every parent controller must have `get{SINGULAR}Action($id)` method
where {SINGULAR} is a singular form of associated object in /var/www/html/cdpaccess/src/ICC/ProposalBundle/Res
ources/config/routing.yml (which is being imported from "/var/www/html/cdpaccess/app/config/routing.yml").
[InvalidArgumentException]
Every parent controller must have `get{SINGULAR}Action($id)` method
where {SINGULAR} is a singular form of associated object
The weird thing is, if I modify routing.yml and set the parent resource on cah_annotation to proposal:
cah_annotation:
parent: proposal
It works fine. Even if I delete the proposal resource entry all together I get the same error.
What am I doing wrong here? These controllers are very similar, how is it that it works with the proposal resource but not standard_proposal?
I am using friendsofsymfony/rest-bundle 1.7.2.
I did see this question already. This does not appear to be the same issue as I worked through that one already.
Maybe you are forgetting add, in the nested Entity, the nested ID parameter in this get{SINGULAR}Action($id):
class SubEntityController
{
...
getSubEntityAction($subId, $id) {
...
}
}
... getSubSub....($subSubId, $subId, $id) ... an so on, on each nested entity.
This one Works for Me.
As the title says I'm getting an error in Laravel 5.0 whilst trying to upgrade a Laravel 4.2 application.
The exact error message is: Call to undefined method Illuminate\Database\Query\Builder::orders()
I get the error when I try to fetch an authenticated users orders from a controller with the following line:
$this->user->orders()->orderBy('created_at', 'desc')->get()
A parent class sets $this->user as:
$this->user = Auth::user();
The user models relationship to orders is:
public function orders()
{
return $this->hasMany('App\Models\Order');
}
To confuse me even more $this->user->orders() returns the error I'm experiencing where as User::whereId($this->user->id)->first()->orders() returns the orders I was expecting.
When I dump both $this->user->orders() and User::whereId($this->user->id)->first()->orders() I get exactly the same output on screen.
Can anyone explain this and possibly point me towards the correct way to do this as my solution feels hacky and I'm sure there is a much cleaner way to accomplish what I'm trying to do.
Thanks
Apologies for answering my own question again, however I have found the proper soloution to my issue.
I had left the default User model in the App folder since installing Laravel 5, and this is the user model Laravel was using when I called Auth::user().
I needed to change config/auth.php to use my customised User Model and all is working as expected.