2

Is there a way with laravel and algolia package to update to the index not ALL the fields but only the ones i need?

mocheaz
  • 29
  • 7

2 Answers2

1

You can use getAlgoliaRecord() method in your model and return array from it with attributes you want to index.

Example:

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use AlgoliaEloquentTrait;

    public function getAlgoliaRecord()
    {
        return [
            'indexedAttribute' => $this->indexedAttribute, 
            'otherIindexedAttribute' => $this->otherIindexedAttribute, 
            'nextIndexedAttribute' => $this->nextIndexedAttribute, 
        ];
    }
}
Jan Petr
  • 685
  • 5
  • 11
  • may I ask you to take a look at a Laravel search related question here: https://stackoverflow.com/questions/76485513/laravel-search-with-multiple-keywords-against-multiple-columns-with-the-search ? – Istiaque Ahmed Jun 15 '23 at 22:19
0

@JanPetr answer is correct but only for laravel 4.

For Laravel 5.3 and above,

As mentioned in docs

By default, the entire toArray form of a given model will be persisted to its search index. If you would like to customize the data that is synchronized to the search index, you may override the toSearchableArray method on the model.

<?php
 
namespace App;
 
use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;
 
class Post extends Model
{
    use Searchable;
 
    /**
     * Get the indexable data array for the model.
     *
     * @return array
     */
    public function toSearchableArray()
    {
        $array = $this->toArray();
 
        // Customize array...
        $array = [
            'post_name' => $this->post_name,
            'post_author' => $this->author,
            'publisher' => $this->publisher,
            'publishing_date' => $this->published_at
        ];

        return $array;
    }
}
bhucho
  • 3,903
  • 3
  • 16
  • 34