Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

masonfox's avatar

Customize User Retrieval

Taylor has outlined a spot in the Spark documentation where you can modify the return of the global user object. It says that you can use to change it:

Spark::swap('UserRepository@current', function () {
    // Return the current user...
});

Here is what I have so far:

Spark::swap('UserRepository@current', function () {
  
  $user_id = Auth::user()->id;
  
  if (Auth::user()->type == 1) {
    // is an employer
    Auth::user()->jobs = User::find($user_id)->employer->jobs->toArray();

    return Auth::user();
  }
});

This will show correctly when I dd it right after the query, but will not show when I call dd(Auth::user()) globally.

Any info on this process would be awesome. Thanks!

0 likes
5 replies
EventFellows's avatar

I think it is mentioned that any ServiceProvider works.

The SparkServiceProvider works for sure (this is where I put it).

masonfox's avatar

@EventFellows , I'm still having a hard time getting the data to stay in the user object. Would you mind sharing your code that you put into your SparkServiceProvider? Here is what I have so far:

        Spark::swap('UserRepository@current', function () {
          
          $user_id = Auth::user()->id;
          
          if (Auth::user()->type == 1) {
            /**
             * is employer
             */
            Auth::user()->jobs = User::find($user_id)->employer->jobs->toArray();
            
            return Auth::user();
          }
        });
EventFellows's avatar

I am doing it for the validation fields for the user registration.

It looks like this in the SparkServiceProvider:

        Spark::swap('CreateUser@rules', function () {
            return [
            'name' => 'required|unique:users,name|min:5|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|confirmed|min:6',
            'vat_id' => 'max:50|vat_id',
            'terms' => 'required|accepted',
            ];
        });
masonfox's avatar

I'm having the same issue where if I add it with the swap, it will show when I dd it right after the query, but it still does not want to actually show in the global scope. I have no clue.

If anyone has actually done this and could pass their example, that would be awesome. Thanks!

masonfox's avatar

@TaylorOtwell or @jeffery, it wouldn't be bad to see something more on this in the Spark Docs or in a future Spark series. Any help is appreciated!

1 like

Please or to participate in this conversation.