I am developing a client portal application using Angular-7 as frontend and Laravel-5.8. I am using Larave Spatie for User Management. I have these three tables:
CREATE TABLE `company` (
`id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`company_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`company_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `trips` (
`id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`dispatch_datetime` datetime DEFAULT NULL,
`loading_date` date DEFAULT NULL,
`loaded_from` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`destination` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`company_id` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `users` (
`id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`company_id` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
From the tables above, I have three classes: User, Company and Trip.
Each user belong to a company, but not more that one.
Each company embark on several trips.
company_id in company is also a Primary Key.
From the ApiController, I have used Laravel Spatie to enable users to only have access to data they are given permission. This is working perfectly:
ApiController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Trip;
use App\User;
use App\Company;
use Illuminate\Support\Facades\Auth;
class TripController extends Controller
{
public function index(Request $request){
if(!Auth::user()->hasPermissionTo('View Trip')){
return response()->json([ "message" => 'User do not have permission'], 401);
}
if(($request->get('sort')!='null' && $request->get('sort')!='') && $request->get('search')){
$trip = Trip::where("trip_number", "LIKE", "%{$request->get('search')}%")->orderby($request->get('sort'), $request->get('order'))->paginate(10);
} else if(($request->get('sort')!='null' && $request->get('sort')!='')){
$trip = Trip::orderby($request->get('sort'), $request->get('order'))->paginate(10);
}
else if($request->get('search'))
$trip = Trip::where("trip_number", "LIKE", "%{$request->get('search')}%")->paginate(10);
else
$trip = Trip::paginate(10);
return response()->json($trip, 200);
}
}
Now, I want to achieve the following from the code above:
The Logged-in user should be able to view only the trips that his company embark on.
If the Logged-In user belongs to the Company that has company_id as MBB, he should be able to view all the trips for all the companies in the database, except he doesn't have permission to view trips.
How can I modify my code to achieve this?