我需要在用户登录时向User模型添加一个自定义属性。该值不在数据库中,因此需要在之后添加。
我需要添加的属性称为client_id
我到处都在寻找解决方案,但是我尝试过的所有方法都无效。当我将用户转储到另一个控制器中时,看不到添加的属性。
我已经剥离了所有尝试过的东西,剩下的就是原始模型。
这是我的用户模型
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $connection = 'mysql';
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['username'];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
];
protected $appends = ['client_id'];
public function getClientIdAttribute()
{
// get the orgId from the session
$client_id = \Session::get('client_id');
return $client_id;
}
}
这是我的LoginContorller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use \DB;
// Models
use App\User;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function login(Request $request)
{
// Check validation
$this->validate($request, [
'username' => 'required|regex:/^([a-z0-9-_\.]+)*@([a-z0-9-]+)$/',
'password' => 'required'
]);
$user = User::where('username', $request->input('username'))
->where('isActive', 1)
->first();
// Set Auth Details
\Auth::login($user);
// Redirect home page
return redirect()->route('dashboard');
}
}
我在$user->setAtttribute('client_id', 12345);
之前使用\Auth::login($user);
绑定了一个属性,但这没用
答案 0 :(得分:0)
您可以像这样在用户模型中创建动态属性。
public function getClientIdAttribute(){
// Write code to return the client ID here
}
然后您可以通过执行$user->client_id
您可以为任何经过身份验证的用户存储值。您可以在应用程序中的任何位置使用全局Laravel session()
帮助程序,如下所示:
// Storing / Setting a Value
session(['client_id' => '12345']);
// Retrieving a Value
session('client_id');