I have a relationship where I am segmenting by language and outputting to the user with postman. But a relationship that I don’t want also comes with it. I tried to remove it with unset but it didn’t work, I’m just trying to filter by language.
If you suggest another method, I can try that too
my db
{"en":"English Machine Name","tr":"Türkçe Makine Adı"}
public function all(Request $request)
{
$locale = $request->header('Accept-Language', App::getLocale());
$searchValue = $request->input('search_value');
$favoriteAll = Favorite::where('user_id', Auth::id())
->when($searchValue, function ($query) use ($searchValue) {
$query->with(['favoriMachine' => function ($query) use ($searchValue) {
$query->where('name', 'like', '%' . $searchValue . '%')
->orWhere('address', 'like', '%' . $searchValue . '%');
}]);
})
->get();
$result = $favoriteAll->map(function ($favorite) use ($locale) {
if ($favorite->favoriMachine) {
$favorite->favoriMachine = $favorite->favoriMachine->map(function ($machine) use ($locale) {
return [
'id' => $machine->id,
'name' => $machine->name[$locale] ?? $machine->name['en'] ?? $machine->name,
'description' => $machine->description[$locale] ?? $machine->description['en'] ?? $machine->description,
'images' => $machine->images,
'location' => $machine->location,
'address' => $machine->address,
'lat' => $machine->lat,
'lng' => $machine->lng,
'dealer_id' => $machine->dealer_id,
'is_active' => $machine->is_active,
'type' => $machine->type
];
});
}
return $favorite;
});
return response()->json([
'status' => 200,
'message' => 'Success',
'data' => $result
]);
}
I tried deleting it with unset, I tried uninstalling it with return, but it didn’t work at all.
2
Answers
Source: https://laravel.com/docs/11.x/eloquent-serialization#hiding-attributes-from-json
if you want to hide ‘favoriMachine’ table data but you want to check some condition use ‘whereHas’
source: https://laravel.com/docs/11.x/eloquent-relationships#querying-relationship-existence