Skip to content
Advertisement

Trying to output a filename through a one to many relationship in Laravel

I am getting the error

call to a member function documents() on boolean

As I am trying to get the filename of the uploaded document for a card. I have created a relationship between Cards and CardDocuments:

Cards.php:

public function documents()
{
    return $this->hasMany(CardDocuments::class);
}

CardDocuments.php:

public function files()
{
    return $this->belongsTo(Card::class, 'card_id');
}

After doing that I used this in the view:

@foreach ($cards as $card)
    {{ $card->documents()->filename }}
@endforeach

And the card_document migration:

Schema::create('card_documents', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedBigInteger('card_id')->unsigned()->index();
    $table->foreign('card_id')->references('id')->on('cards');
    $table->string('filename')->nullable();
    $table->timestamps();
});

Not sure why this is showing a boolean error as the file submission for this works and the files are saved successfully to the database so can’t understand why I can’t access documents() to get the filename to output.

Advertisement

Answer

I think that documents are nested array:

        @foreach ($cards as $card)
            @foreach ($card->documents as $document)
                {{ $document->filename }}
            @endforeach
        @endforeach
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement