John Davidson

php - Laravel: Check for Specific Pivot Relation OR no relation

0 comments
Message:


I'm using Laravel 8.0


I have two tables, Module and User, linked by a pivot table (module_user), I'm trying to work out how to list ALL of the modules using eloquent (or SQL) and if the current user has a pivot entry (e.g. they have completed the module) then it marks that, for example:


Module Name         Completed
########### #########
Coding Basics
Database Basics Yes

Any suggestions? I really have no idea how to go about this as I either retrieve ALL the linked modules/users or only the modules the current user has completed.


Thanks!!



My Answer:
You can achieve this by using the `withPivot` method in your relationship definition in your Laravel models. Here's an example of how you can do this:

In your `Module` model, define the relationship with the `User` model like this:

php
public function users()
{
return $this->belongsToMany(User::class)->withPivot('completed');
}


Then, you can retrieve all modules and check if the current user has completed each module like this:

php
$modules = Module::with(['users' => function ($query) use ($userId) {
$query->where('id', $userId);
}])->get();

foreach ($modules as $module) {
$completed = $module->users->first()->pivot->completed ?? 'No';
echo $module->name . ' - Completed: ' . $completed . '
';
}


In this code snippet, replace `$userId` with the ID of the current user. This will retrieve all modules and check if the current user has completed each module. If the user has completed the module, it will display 'Yes', otherwise it will display 'No'.

I hope this helps! Let me know if you have any questions.

Rate this post

3 of 5 based on 8854 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us