Laravel 8.x从Algolia拉取用户数据时调用模型方法报错
问题
Laravel 8.x项目中,从Algolia拉取已同步的users表数据时,将结果转为stdClass对象后,视图调用getCustomField()和getSocialIcons()方法报错:Call to undefined method stdClass::getCustomField()。核心原因是从Algolia获取的是普通对象,而非User模型实例,无法调用模型中定义的方法。
解决方案
方案1:使用Laravel Scout查询(推荐)
你的User模型已经引入Searchable trait,直接用Scout的查询方法,自动返回模型实例:
修改CreatorController的show方法:
public function show($username) { $creator = User::search($username)->first(); if (!$creator) { abort(404); } return view('creators.show', compact('creator')); }
Scout会自动处理Algolia查询,返回User模型实例,可直接调用模型内的所有方法。
方案2:手动将Algolia数据填充到User模型实例
若坚持使用原生Algolia客户端,将获取到的数组数据填充到User模型:
public function show($username) { $client = SearchClient::create( env('ALGOLIA_APP_ID'), env('ALGOLIA_SECRET'), ); $index = $client->initIndex("users"); $creatorData = $index->search($username); $creatorArray = $creatorData["hits"][0] ?? null; if(!$creatorArray){ abort(404); } // 创建User模型实例并填充基础属性 $creator = new User(); foreach ($creatorArray as $key => $value) { // 跳过Algolia自带的特殊字段 if (!in_array($key, ['objectID', '_tags'])) { $creator->$key = $value; } } // 适配customFields关联,让getCustomField方法正常工作 $creator->setRelation('customFields', collect($creatorArray['custom_fields'] ?? [])->map(function ($value, $key) { $field = new \App\Models\UserCustomField(); $field->key = $key; $field->value = $value; return $field; })); return view('creators.show', compact('creator')); }
处理后$creator为User模型实例,可正常调用模型方法。
方案3:修改视图逻辑适配Algolia数据结构
若不想修改控制器,直接在视图中读取Algolia返回的custom_fields数组:
<div class="flex items-center space-x-4"> @foreach(['linkedin','instagram','twitter','podcast','youtube','website'] as $value) @if(isset($creator->custom_fields[$value])) <a href="{{ $creator->custom_fields[$value] }}" target="_blank"> <img src="{{ asset(match($value) { 'linkedin' => 'assets/images/icon-linkedin.svg', 'instagram' => 'assets/images/icon-instagram.svg', 'twitter' => 'assets/images/icon-twitter.svg', 'podcast' => 'assets/images/icon-podcast.svg', 'youtube' => 'assets/images/icon-youtube.svg', 'website' => 'assets/images/icon-website.svg', default => '' }) }}" alt="{{ ucfirst($value) }}"> </a> @endif @endforeach </div>
直接使用Algolia返回的custom_fields结构,无需依赖模型方法。
内容的提问来源于stack exchange,提问作者iguner
相关产品推荐
相关产品推荐

