1 year ago
#165627
Zahra19977
Making a new attribute in Algolia using Laravel Scout's toSearchablaArray() doesn't work
I want to make a new attribute called categories
for the categories of the product in Algolia
, So I use toSearchableArray()
:
<?php
use Laravel\Scout\Searchable;
class Product extends Model
{
use Searchable;
//...
public function categories(){
return $this->belongsToMany(MyCategory::class);
}
/**
* Get the indexable data array for the model.
*
* @return array
*/
public function toSearchableArray()
{
$array = $this->toArray();
$extraFields = [
'categories' => $this->categories->pluck('name')->toArray(),
];
return array_merge($array, $extraFields);
}
}
When I reset migration and seed, I see that categories
attribute contains empty array.
categories: [],
I also tested with tinker
and worked:
App\Models\Product::find(1)->toSearchableArray();
/* returns
[
"id" => 1,
"name" => "Laptop1",
"slug" => "laptop-1",
"details" => "15inch, 1TB SSD,3GB RAM",
"price" => 22367,
"description" => "Lorem1 ipsum dolor sit amet, consectetur adipisicing elit. Ipsum temporibus iusto ipsa, asperiores voluptas unde aspernatur praesentium in? Aliquam, dolore!",
"created_at" => "2022-02-11T07:06:57.000000Z",
"updated_at" => "2022-02-11T07:06:57.000000Z",
"featured" => 0,
"image" => null,
"categories" => [
"Laptops",
"Desktops",
],
]
*/
Why categories
contains empty array in Algolia
and how can I fix It?
Thanks
algolia
laravel-scout
0 Answers
Your Answer