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.
Related
I have three models user,roles,model_has_roles,when i assign any role to the user from the roles table it's creating an instance of the model in model_has_roles table.I am using removeRole() laravel method for removing roles ,i am giving some details what are the roles present inside my database like(super-market,notification,all...).it's deleteing all roles except notification,all.
$roleName = implode(' ,',$roleName); // "super-market" or "all"
foreach ($roles->pluck('name')->toArray() as $roleName) {
$user->removeRole($roleName);
}
Now what i need is irrespective of the role(any role) i want to delete that role ,some of the roles it's deleteing and remove the instance of the model from the model_has_roles and some of the roles are not deleted (for example all,notification),please help me to fix this issue
there is no built-in laravel package for managing roles and permission and removeRole() is not in laravel (I dont know why you did wrote removeRole laravel method ), there is a package called laravel-permission that has the same table design of yours. if you are using this package you can find docs in here. if you are writing your own try debugging it with dd() and tinker to find out what's wrong with some that they won't be deleted.
I got it reverse in first place, you must use explode instead, and move first line into foreach loop
foreach ($roles->pluck('name')->toArray() as $roleName) {
$roleName = explode(',',$roleName);
$user->removeRole($roleName);
}
In a fresh installation of Laravel 8.20.1, I have created two models Company and User with a pivot table between to facilitate a many-to-many relationship. The pivot has a role attribute.
I can add a user to a company using:
$company->users()->attach($user);
I've added a utility method addUser so that I can first check existence of the relationship to avoid duplication:
public function addUser(User $user) {
if($this->users->contains($user)) {
// if the user already has a role, update it
Log::info("User #{$user->id} present - updating");
$this->users()->updateExistingPivot($user, ['role' => 'user'], true);
} else {
// if the user doesn't have a role, add it
Log::info("User #{$user->id} not present - adding");
$this->users()->attach($user, ['role' => 'user'], true);
}
}
The first time I run this using a refreshed database, it should see that the user is not yet related to the company and run the else part of the switch to add a new user. Running this in Tinker, it appears to do this - and the logs show 'User #1 not present - adding' - but when I check for presence using contains, it returns false:
$user = User::factory()->create();
$company = Company::factory()->create();
$company->addUser($user);
print_r($company->users->contains($user)); //false
I've tried logging the queries for this function, and I they look fine - one for checking existence of the user, a second for inserting the pivot.
Also, I can see a pivot record for user #1 and company #1, and if I then test this in Tinker, I get true:
print_r(Company::find(1)->users->contains(User::find(1))); // true
It's almost as if the database is running async, which I know isn't the case in PHP. I'm using Sqlite v3.31.0.
The issue is definitely in my addUser method, as if I replace this call in Tinker with calling attach directly, it works.
I'm really keen to use this utility method (and others), because:
I want to avoid multiple pivot records for the same company/user (without using compound indexes)
I need several more utility methods such as addAdmin, addOwner, etc
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.
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.
I'm starting to learn Laravel. I've run through the example instructions from the site successfully and now I'm trying a second run through and I'm running into an issue.
I'm trying to connect to a database called zipCodes and has one table called zipCodeDetails.
In my Laravel project I have a model containing the following code:
<?php
class ZipCodeDetails extends Eloquent {}
And in my routes.php file I have the following code:
Route::get('zipCodes', function (){
$zipCodes = ZipCodeDetails::all();
return View::make('zipCodes')->with('zipCodes', $zipCodes);
});
The error I'm running into is when I try to load the URL:
http://localhost:8888/zipCodes
In my browser I'm getting the error code:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'zipcodes.zip_code_details' doesn't exist (SQL: select * from `zip_code_details`)
There's nothing written in my code where I define the database zipCodes as zipcodes or the table zipCodesDetails as zip_code_details. Something in laravel is changing the database and table names.
Does anyone know why this is happening and how I can prevent it? I don't want to just rename the database or table names because while that may get me by in testing it's not a viable solution in practice.
Thanks!
This is the behaviour that uses if no table is being explicitly defined. In your ZipCodeDetails class, you can set the table name that this model will be using.
class ZipCodeDetails extends Eloquent
{
protected $table = 'zipCodesDetails';
}