Proper way to add some custom methods to Tailor model

Hi, I know there are several posts on pointing the differences and use cases for Tailor vs. regular models. This question is a bit more specific though. In fact I love tailor and its speed and want to make sure I use it everytime is the way to go. Here goes an example: I used to have a custom plugin for blog, where I had added some custom methods for getting the next and previous models. In my Post model php file I had:

// Previous / Next
    public function scopeApplySibling($query, $direction)
    {

        $directionOrder = ($direction == '1') ? 'asc' : 'desc';
        $directionOperator = ($direction == '1') ? '>' : '<';

        $query->where('id', '<>', $this->id);
        if (!is_null($this->created_at)) {
            $query->where('created_at', $directionOperator, $this->created_at);
        }

        return $query->orderBy('created_at', $directionOrder);
    }

    /**
     * Returns the next post, if available.
     * @return self
     */
    public function nextPost()
    {
        return self::Publicados()->applySibling(1)->first();
    }

    /**
     * Returns the previous post, if available.
     * @return self
     */
    public function previousPost()
    {
        return self::Publicados()->applySibling(-1)->first();
    }

The feature itself is not relevant, but I would like to know if there´s a way to extend / add custom logic through custom methods (like those for example) to a Tailor model.

Thanks!

Yes, I found out away

Extend your model class from EntryRecord as the following:

class Post extends EntryRecord
{
  protected $handle = 'ABCD\Post';
       
     
  public function __construct()
  {
      $uuid = BlueprintIndexer::instance()->findSectionByHandle($this->handle)->uuid;
      $this->extendWithBlueprint($uuid);
      parent::__construct();
  }

then use your new model to fetch the data as normal.

Post:where(...)
2 Likes

This is a good solution!

One more thing to add. To handle attachments and morph relations with the customer Model, you will have to add the following method.

  public function getMorphClass()
  {
      return EntryRecord::class . '@' . $this->table;
  }