2
votes

Actually, my question is very simple but I couldn't find any answer.

I'm using Laravel eloquent, I have 3 tables:

company_types
-id
-name

document_types
-id
-name

and a pivot table called:

company_type_document_type
-company_type_id
-document_type_id
-is_default

I already have the company_type_id from my company object and I'm trying to get the name of the document_type like this:

controller...
$document_type = CompanyTypesDocumentTypes::where('company_type_id',$company->company_type_id)->with('document_type')->where('is_default',true)->first();

view...
{{ $document_type->name }}

I'm sure that the problem is with my models, but the issue is that I don't really understand when to user "hasMany" or "BelongsToMany" etc... In Addition, I think that there might be a problem with the name of the pivot table cause there are too many underscores

thank you for your help!

1

1 Answers

2
votes

Since it's many-to-many, you should use wherePivot() method.

Define the relationship:

public function defaultDocumentTypes()
{
    return $this->belongsToMany(DocumentType::class)->wherePivot('is_default', 1);
}

Then you can get document types using this relationship:

$companyType = CompanyType::find($companyTypeId);
$documentTypes = $companyType->defaultDocumentTypes()->get();

Display them in the view:

@foreach ($documentTypes as $documentType)
    {{ $documentType->name }}
@endforeach