Hi, did you solve this?
Laravel - Many to Many Relationship & Policies
I'm relatively new to Laravel and am trying to learn as fast as I can but recently came across an issue that I just can't seem to shake.
I have 3 tables with the relevant fields for this post:
- Users - id
- Shipment_User - shipment_id, user_id
- Company_User - company_id, user_id
- Companies - id
Because of complexities, I have been suggested by a friend to handle the following through a policy, rather than middleware (however, if one of you has a suggestion, I'm willing to look into it of course :)). Anyways, what I would like to do is have a policy (which I will lay out the current one I have below) where if a user is attached to any number of companies, they can see all of the shipments attached to those companies (and on my Shipment, User and Company models, I do have the relationships laid out as "belongsToMany").
So assume the following
Shipment #|Company ID(pivot table: company_shipment)
1 | 1
2 | 1
3 | 2
4 | 3
Then User #1, who is associated through the pivot table (company_user) to companies 1 and 2, can see shipments 1, 2, and 3, but not 4.
Here is my ShipmentPolicy that I have created so far:
<?php
namespace App\Policies;
use App\User;
use Auth;
use App\Shipment;
use App\Company;
use Illuminate\Auth\Access\HandlesAuthorization;
class ShipmentPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view the shipment.
*
* @param \App\User $user
* @param \App\Shipment $shipment
* @return mixed
*/
public function view(User $user, Shipment $shipment)
{
$user_company = Auth::user()->companies()->pluck('id');
$shipment_company = $shipment->companies->pluck('id');
return $shipment_company == $user_company;
}
/**
* Determine whether the user can create shipments.
*
* @param \App\User $user
* @return mixed
*/
public function create(User $user)
{
//
}
/**
* Determine whether the user can update the shipment.
*
* @param \App\User $user
* @param \App\Shipment $shipment
* @return mixed
*/
public function update(User $user, Shipment $shipment)
{
//
}
/**
* Determine whether the user can delete the shipment.
*
* @param \App\User $user
* @param \App\Shipment $shipment
* @return mixed
*/
public function delete(User $user, Shipment $shipment)
{
//
}
}
Now, my problem arises from the issue that if a user is added to one company, they can view the shipments just fine, however, if they are added to 2 (which is as far as I bothered to test), it fails and it returns an error.
So my questions are:
- What must I change in how I am handling the set-up of this current policy, and
- Would there be a better way of handling this issue rather than policies, or with something else in conjunction with policies?
Thanks in advance for any help anyone can provide.
Thanks!! Chase
Please or to participate in this conversation.