gpt4 book ai didi

php - Laravel 如何使用 auth :user() 返回选定的列

转载 作者:行者123 更新时间:2023-12-01 10:21:28 24 4
gpt4 key购买 nike

这几天开始用Passport学习Laravel,关注了这篇精彩的文章Create REST API in Laravel with authentication using Passport .

我已经创建了登录、注册、详细信息列表 API,但在登录 API 中,我试图以 JSON 格式返回登录的用户详细信息,它返回所有信息,但我只想要 id, name, email, phone那么如何申请select('id', 'name', 'email', 'phone')$user = Auth::user()
我可以使用 PHP unset 函数轻松删除数据,但我不想使用它。我只想选择需要的列,所以有可能吗?

我的 Controller 源代码:

<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class PassportController extends Controller
{
public function login()
{
if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')->accessToken;

return response()->json(['data' => $user, 'success' => $success], 200);
} else {
return response()->json(['error' => 'Unauthorised'], 401);
}
}
}

API JSON 结果:
{
"data": {
"id": 1,
"name": "Abraham Hess",
"first_name": "Abraham",
"last_name": "Hess",
"phone": "982595360",
"email": "abraham@mailinator.com",
"username": "abraham",
"created_at": "2018-05-29 16:58:55",
"updated_at": "2018-05-29 16:58:55"
},
"success": {
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjFiYjQ3OWY3MzlkZTAxNjc0Njc4Nzg3Mjg2ZTU4NGI0NjljNjE2OGUxNGUyZWUzYmJlOWViMWIwMTUxMzhhZWI3ODU0NjViNTgzZTQ5ZjVlIn0.eyJhdWQiOiIxIiwianRpIjoiMWJiNDc5ZjczOWRlMDE2NzQ2Nzg3ODcyODZlNTg0YjQ2OWM2MTY4ZTE0ZTJlZTNiYmU5ZWIxYjAxNTEzOGFlYjc4NTQ2NWI1ODNlNDlmNWUiLCJpYXQiOjE1MzIwMjExMDYsIm5iZiI6MTUzMjAyMTEwNiwiZXhwIjoxNTYzNTU3MTA2LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.KpaU10j9mrvgLarYODEza9fd6f_7YI99GabnSIZj370M439abxqQWuQHH9LhUWy1OuFVaj5wt-BC0UIbirI3nkVaqgfwoldMT_xijv6ZuL0glLAvaNOfZwO-Oox8zZO1cDL35g49GT3MNqd8iFD6zLnaDrljsB_pkL2PVOqgRwdIVLamR_VUy_EvxhQhXPBsRrEVYQS1gGLj-voPV7iMZyTU4QrmnPZC1n_ChPZDt4nSUT__UDgXS7Bw0pV5RI03c91Lk_cOvgCbBZsLpYO1LtlXs-rKUoUbWr17xaAJ1MoPHeNVUHw931_ZOkwVX_gW_rimZWdQTuTOZwTVh4kV8rldR4IghDSY4kCVQccO_p6rAQrwy5qD-godkMxwn8mee8zsWpusPhfbJ_iWZH3LKDTHwKCBq6v4GUGipJTXgbiiBPg-MZ_bVjl2rPPdHRXMPpvMtxJChTeZ71tfVu7AbJ2GHvHU6gVm3RyEPDeGgmBt1WdyDi49Gw8weym8t5o-g33JAPLEOa73lg8h36NtFVmbXAR2P5oIV8pG1PXUNCtcGu_Lz8Zq1Kd-7AJBsFzMIELgRG2_CJCzEpir91cM9xfId-iqXQ7Vw1QWs8RDM5A7vESRh17UHcKHXyFk4srT0TGLkjTtsifUv6sA2AcHw3yJF6gc3nZoalTSghzJqA4"
}
}

最佳答案

你可以用 ->only 来做:

return response()->json([
'data' => $user->only(['id', 'name', 'phone', 'email']),
...
]);

关于php - Laravel 如何使用 auth :user() 返回选定的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51428910/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com