首页 > 解决方案 > Laravel - 隐藏特定列

问题描述

我想隐藏包含在s 结果中的列password& 。实际上,这 2 列是 users 表的一部分。我的最终需要是我需要加入 3 个表:,,并希望隐藏用户表中的&列。可以使用任何方法。通过任何方法,我想达到这个结果我尝试了很多方法。没有任何效果。如何解决这个问题?有什么建议么..OTP$useruserslocationuser_technical_detailspasswordOTP

我尝试过的事情:

1)

$users = DB::table('users')
            ->join('location', 'users.id', '=', 'location.id')
            ->join('user_technical_details', 'users.id', '=', 'user_technical_details.id')
            ->get();
$d=$users->makeHidden(['password','OTP']);    
return response()->json([
            'message' => 'profile viewed successfully',
            'data' => $d,
            'statusCode' => 200,
            'status' => 'success'],200);

这会产生错误 -Method Illuminate\\Support\\Collection::makeHidden does not exist

2)

$users = DB::table('users')
            ->join('location', 'users.id', '=', 'location.id')
            ->join('user_technical_details', 'users.id', '=', 'user_technical_details.id')
            ->get();
            
$exclude_columns=['password','OTP'];
        $get_columns = array_diff($users, $exclude_columns)->get();
return response()->json([
                'message' => 'profile viewed successfully',
                'data' => $get_columns,
                'statusCode' => 200,
                'status' => 'success'],200);

3)

$users = DB::table('users')
            ->join('location', 'users.id', '=', 'location.id')
            ->join('user_technical_details', 'users.id', '=', 'user_technical_details.id')
            ->get();
 $d=collect($users->toArray())->except(['password','OTP']);    
   return response()->json([
                'message' => 'profile viewed successfully',
                'data' => $d,
                'statusCode' => 200,
                'status' => 'success'],200); 

4)

protected $hidden = ['密码','OTP'];

5)

$users = DB::table('users')->exclude(['password','OTP','ph_OTP','email_OTP','user_access_token','remember_token'])
            ->join('location', 'users.id', '=', 'location.id')
            ->join('user_technical_details', 'users.id', '=', 'user_technical_details.id')
            ->get();
            return response()->json([
                'message' => 'profile viewed successfully',
                'data' => $users,
                'statusCode' => 200,
                'status' => 'success'],200);

这会产生错误 -Call to undefined method Illuminate\\Database\\Query\\Builder::exclude()

标签: phplaravelpostgresqleloquentlaravel-8

解决方案


当您想要限制包含在模型数组或 JSON 表示中的属性(例如密码)时。为此,请将$hidden属性添加到您的模型中。在 $hidden 属性的数组中列出的属性将不会包含在模型的序列化表示中:

class User extends Model
{
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = ['password','OTP'];
}

现在在您的代码中,您必须使用用户模型而不是 DB 外观:

$users = User::query()
            ->join('location', 'users.id', '=', 'location.id')
            ->join('user_technical_details', 'users.id', '=', 'user_technical_details.id')
            ->get();

现在,$users不会有隐藏属性


推荐阅读