Alexander
Alexander

Reputation: 290

Model Relationship issue in Laravel

I am learning model relationships in Laravel. I am having the following issue:

I have a table for 'NPIData' with primary key as NPI

I have a table for 'Users' with primary key as id

I have a table for 'UserToProviderMapping' with two columns, one for user_id (maps to id on users table) and one for provider_npi (maps to NPI on NPIData table).

I have the following code in my controller:

    public function index()
{
    //
    $user = Auth::id();
    $providers = UserToProviderMapping::where('user_id', $user)->get();

    return view ('my-health-hub', compact('providers'));
}

I have the following code in my view currently (obviously incomplete)

@foreach($providers as $provider)

 <li>{{$provider->provider_npi}}</li>

@endforeach

I am not sure if I can use a model relationship here because I have added another table in between the two models (users and NPIData). I am trying to get the provider_npi from the UserToProviderMapping table and use that to look up the data within the NPIData table and loop through.

Upvotes: 0

Views: 34

Answers (1)

Hafez Divandari
Hafez Divandari

Reputation: 9029

Many-to-many relationship is what you are looking for:

Define the providers method on your User model like this:

class User extends Model
{
    /**
     * The providers that belong to the user.
     */
    public function providers()
    {
        return $this->belongsToMany(
            'App\NPIData', 
            'user_to_provide_mappings', // the table name of the relationship's joining table (pivot table)
            'user_id',                  // the foreign key name of the model (on the pivot table) on which you are defining the relationship
            'provider_npi',             // the foreign key name of the model (on the pivot table) that you are joining to
            'id',                       // the primary key name of the model on which you are defining the relationship
            'NPI'                       // the primary key name of the model that you are joining to
        );
    }
}

Then on your Controller:

use Illuminate\Http\Request;

public function index(Request $request)
{
    $providers = $request->user()->providers()->get();

    return view('my-health-hub', compact('providers'));
}

Optional: You may define your custom intermediate model UserToProviderMapping as described in the docs: https://laravel.com/docs/master/eloquent-relationships#defining-custom-intermediate-table-models

Upvotes: 1

Related Questions