I am building a logistic app. I have 3 tables that look like this: users: UserID service: ServicesID providers_services: ProviderID, ServiceID providers_services table contains all services in the application provided by providers(users). that's means when a user register in the app as a provider they will select services that they will provide these stores into the providers_services table. a single user could have many services that they provide. in the dashboard, I fetch all users from the user's table (in blade view) and a select option with all services. I want when I select a service the table should be filtered and show me only the users (providers) that they provide the selected service.
This is my code:
[![enter image description here][1]][1]
public function getForm(Request $request)
{
$getSerName = $request['ServiceName'];
$dataReqServices = DB::table('service')
->join('category','category.CategoryID','=','service.CategoryID')
->get();
$users = DB::table('users')
->join('providers_services','providers_services.ProviderID','users.UserID')
->where('users.UserID','=',$getSerName)
->get();
return view('push.notify', compact('users','dataReqServices'));
}
You can use many to many relationships. Make sure you have this in your User model:
public function services()
{
return $this->belongsToMany(Service::class);
}
And this in your Service model:
public function users()
{
return $this->belongsToMany(User::class);
}
This is service_user_pivot_table content:
Schema::create('service_user', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('service_id');
$table->unsignedBigInteger('user_id');
$table->timestamps();
$table->foreign('service_id')->references('id')->on('services');
$table->foreign('user_id')->references('id')->on('users');
});
To return users, in your controller use:
public function index($id)
{
$services = Service::find($id);
$users = $services->users;
return view('home', compact('users'));
}
This $id is passed on web.php routes, so it looks like this for me:
Route::get('/home/{id}', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Where id is id of service. Make sure you also add this to your controller:
use App\Models\Service;
on the top.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.