在Laravel API中,我有一些方法,它们返回一些我不想在结果中出现的字段,例如:
id - email - user_id
并且它们是可选的,并且我无法将此字段设置为自模型,现在我将此类用作ManageResource来从类似以下代码的结果中隐藏/删除字段/列:
$user = User::whereApiToken($request->api_token)->first();
$result = ManageResource::make($user)->hide(['id','email']);
在使用下面的类实现的代码后,我仅获得ID和关于数组键的电子邮件,但是我想隐藏它们
ManageResource类:
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
class ManageResource extends Resource
{
/**
* @var array
*/
protected $withoutFields = [];
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request
* @return array
*/
public function toArray($request)
{
return $this->filterFields($this->withoutFields);
}
/**
* Set the keys that are supposed to be filtered out.
*
* @param array $fields
* @return $this
*/
public function hide(array $fields)
{
$this->withoutFields = $fields;
return $this;
}
/**
* Remove the filtered keys.
*
* @param $array
* @return array
*/
protected function filterFields($array)
{
return collect($array)->toArray();
}
}
解决方法:
由于您希望隐藏给定模型实例上的一些通常可见的属性,因此可以使用makeHidden方法.
return $user->makeHidden(‘attribute’)->toArray();
Here, $user represents user model
示例案例:使用带有代码的makeHidden隐藏分页结果中的列
$result = Job::where('user_id','=',Auth::id())->paginate(5);
$data =$result;
$result= $result->makeHidden(['hasMessage']);
$data->data = $result;
return $data;
就您而言:
$result = ManageResource::make($user)->makeHidden(['id','email'])->toArray();
$data->data = $result;
return $data;
要么
$result = User::whereApiToken($request->api_token)->first()->setHidden(['id', 'email']);
$data->data = $result;
return $data;
注意 :
据我所知,makeHidden不会影响关系.如果允许您将关系中的属性指定为-makeHidden([‘relation.field’]),那会很好.或者,您可以使用以下代码
App\Models\Product::with([‘images’ => function ($query) {
$query->select([‘id’,’product_id’,’image_url’,
‘row_id’])->orderBy(‘created_at’, ‘desc’);
}])->get()->makeHidden([‘id’]);
就你而言
$tickets = UserTickets::with(['user', 'reply' => function ($query) use ($user) {
$query->with('user')->select(['id','Attrib1','Attrib2'])->whereUserId($user->id);
}])->whereTicketNumber($request->ticket_number)->get();
标签:laravel,php
来源: https://codeday.me/bug/20191025/1925985.html