Adding data to the Spark Global User
Hey all,
I am working on an app using Spark where I'd like to pass some additional data to the Spark global user object and had some difficulty with it last night. Our app has different user types, the user table being the generic similarity between all of them, so simply adding this data to the users table won't work.
I found a file, spark/src/User.php, which looks to be the Spark user model. At the bottom you'll find function called toArray(). If you dd($array), it will spit out your user's global object, the one you access via Auth::user(). I added my query and pushed the data into this object based on the user type. Should have worked? Kind of.
If I dd the new array from the model, it will show me the object with my new data. It will also show correctly if I call, {{ Auth::user() }} in my view. It will however not work when I try and call that new data, Auth::user()->jobs, where it returns null and it will also not show if I try and dd(Auth::user()) in a view.
Here is the file, spark/src/User.php
<?php
namespace Laravel\Spark;
use App\Jobs;
use App\Offers;
use Illuminate\Support\Str;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Billable, HasApiTokens;
/**
* Get the profile photo URL attribute.
*
* @param string|null $value
* @return string|null
*/
public function getPhotoUrlAttribute($value)
{
return empty($value) ? 'https://www.gravatar.com/avatar/'.md5(Str::lower($this->email)).'.jpg?s=200&d=mm' : url($value);
}
/**
* Make the team user visible for the current user.
*
* @return $this
*/
public function shouldHaveSelfVisibility()
{
return $this->makeVisible([
'uses_two_factor_auth',
'country_code',
'phone',
'card_brand',
'card_last_four',
'card_country',
'billing_address',
'billing_address_line_2',
'billing_city',
'billing_state',
'billing_zip',
'billing_country',
'extra_billing_information'
]);
}
/**
* Convert the model instance to an array.
*
* @return array
*/
public function toArray()
{
$array = parent::toArray();
$array['tax_rate'] = $this->taxPercentage();
// this is where we may want to push a jobs array
// variable for employers into the user model.
// We'd then be able to access it anywhere:
// Auth::user()->jobs
$id = $array['id'];
if($array['type'] == 1) {
// is employer
$array['jobs'] = Jobs::where('employer_id', '=', $id)->get()->toArray();
return $array;
} else {
// is employee
$array['offers'] = Offers::where('employee_id', '=', $id)->get()->toArray();
return $array;
}
}
}
So it seems as if it is being blocked at some point. If anyone has any tips, I would be very very grateful! Thanks!
Please or to participate in this conversation.