winnie damayo
winnie damayo

Reputation: 426

How to get first row in Laravel relationship

How can i create a method in my model below that consist of first value of pages?

I want my cover method to get he first instance of pages.

Here's my model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
   protected $guarded = [];

   public function pages()
   {
       return $this->hasMany('\App\Page');
   }

   public function cover()
   {
       //first page of pages here
   }

}

Upvotes: 2

Views: 5243

Answers (1)

Brian Ail
Brian Ail

Reputation: 66

Use the first() method on the relationship

public function cover()
{
    return $this->pages()->first();
}

Upvotes: 5

Related Questions