How to extend Laravel 5 auth properly?

Laravel 5 extend auth::user() with information from other database table

  • I am using Auth::user() to get information on the current logged in user. Now I want to extend the Information delivered by Auth::user(). Concrete the activation state of the user shall be available. This information is stored in the table activations in the column state. From my understanding Auth::user() delivers what will be retrived from the user model. So I should create a relationship between table users and table activations. The http://laravel.com/docs/5.0/eloquent#one-to-one states 2 posibilites, both require that the activations table has a foreign_key user_id. My table layout does not cover that, I just have refernce in the users table to the actvtion_id. is there a possibilty to build a relationsship with my table layout, which leads to the desired result, that Auth::user() deliveres me the activation state? If how should I do it? Or do I have to switch the table layout as recommended in the documentation? Below my table code: Controller: class ProfileController extends Controller { public function me() { return Auth::user( ); } } users (migration): Schema::create('users', function(Blueprint $table) { $table->increments('id'); $table->string('email')->unique(); $table->integer('activation_id')->unsigned(); $table->foreign('activation_id')->references( 'id' )->on( 'activations' ); //... $table->timestamps(); }); activations (migration): Schema::create('activations', function(Blueprint $table) { $table->increments('id'); $table->string('activationStatus', 1)->nullable()->default('N'); // ... $table->timestamps(); });

  • Answer:

    Firstly, you need to define a model relationship in your User model: public function activation() { return $this->belongsTo('App\Activations', 'activation_id'); } Now, you can easily lazy load the Activation relationship from the authenticated user: $user = Auth::user()->load('activation'); If you want to get the activation status, you can now do: var_dump($user->activation->activationStatus); // Prints 'Y' / 'N'

jerik at Stack Overflow Visit the source

Was this solution helpful to you?

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.