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 documentation 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();
});
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'
Related
So from my previous post, I was advised to start using Eloquent models, which I did.
My end goal, is to print out specific gifts, that belongs to that specific box.
Migrations:
gift_items:
public function up()
{
Schema::create('gift_items', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->float('unit_price');
$table->integer('units_owned');
});
}
gift_campaigns:
public function up()
{
Schema::create('gift_campaigns', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->foreignId('user_foreignK')->constrained('users');
$table->integer('gift_item_count')->nullable();
$table->string('status');
$table->date('dispatch_date');
$table->date('delivery_date');
});
}
Pivot table:
public function up()
{
Schema::create('campaigns_gifts', function (Blueprint $table) {
$table->foreignId('gift_id')->constrained('gift_items');
$table->foreignId('campaign_id')->constrained('gift_campaigns');
});
}
Controller:
function box($id){
$data = Campaign::with('gifts')->where('id', $id)->get();
return view('DBqueries.boxView', ['data'=>$data]);
}
Error that I receive using this way:
Seems like the updated version is trying to call the gift_campaigns table id, instead of the pivots table campaign_id.
Once again, I need that Request $id would match the pivots table campaign_id, and print out all of the gifts that this specific id holds
First of all as I sense the campaigns_gifts is a pivot table for campaigns and gifts having a Many-to-Many relation. You are doing it completely against the conventions of Laravel.
You generally do not use a Model for pivot table.
You generally do not fetch data from the pivot table directly. Instead use the relation on one of the related Models.
Note: Laravel does allow a Model for a Pivot, and you can query the pivot table directly, just check the documentation.
The correct way:
Pivot
Make a pivot table (that you already have) with column gift_id and campaign_id. i.e., the convention for naming keys as [table_name_singular]_[primary_key_on_table]
Model
One each model, define relationship for the other data as:
Gift.php Model:
public function campaign() {
return $this->belongsToMany(Campaign::class, 'campaign_gift');
}
Campaign.php Model:
public function gifts() {
return $this->belongsToMany(Gift::class,'campaign_gift');
}
since gift have a hasMany relation, the gifts table must contain a foreign key to campaigns table named campaign_id (same as the one on pivot).
Controller
Now in your controller:
function box($id){
$data = Campaign::where('id',$id)->with('gifts')->get();
return view('DBqueries.boxView', ['data'=>$data]);
}
You don't need to tell Laravel which columns, tables etc are you referring to, as long as you follow the conventions, Laravel will magically do things that otherwise would have been much more painful.
I need to make a relationship between User and Subscription table.
The user who registers gets a default free user and sees 1 an offer.
If silver see 8 offers, gold 15, platinum 20.
I made a relationship between user and subscription tables with a pivot table subscription_user.
The first question is whether I made a mistake somewhere in relation the model?
The second question is how to return only one offers by default, or if you subscribe to 8 offers (silver), 15 (gold), 20 (platinum) and in which controller?
User table:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('subscription')->default('free');
$table->rememberToken();
$table->timestamps();
});
Subscription table:
Schema::create('subscriptions', function (Blueprint $table) {
$table->increments('id');
$table->string('subscription');
$table->integer('offers');
$table->timestamps();
});
Sabscription_user table:
Schema::create('subscription_users', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->index(); //user table
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); //foreign key relation
$table->integer('subscription_id')->unsigned()->index();
$table->foreign('subscription_id')->references('id')->on('subscriptions')->onDelete('cascade'); //foreign key relation
});
Subscription model:
class Subscription extends Model
{
public function users() {
return $this->belongsToMany('App\User');
}
}
User model:
public function subscriptions(){
return $this->belongsToMany('App\Subscription');
}
Is everything connected as it should be for many to many relationship?
In which controller I can get information about offers?
By convention the pivot table is named singular so you will need to specify by adding a second argument. I like to include all the arguments so there is no guessing anyway.
public function subscriptions()
{
return $this->belongsToMany("App\Subscription", 'subscription_users', 'user_id', 'subscription_id', 'id', 'id');
}
public function users()
{
return $this->belongsToMany("App\User", 'subscription_users', 'subscription_id', 'user_id', 'id', 'id');
}
Yes you should use a controller but it depends on where you are trying to display this. I imagine you will need to display the current subscriptions somewhere as well as add and remove.
I have a table User with column
$table->increments('id');
$table->string('emp_id');
$table->string('email')->unique();
$table->string('password');
And table Employee
$table->increments('id');
$table->string('employee_id')->unique();
$table->string('employee_name');
$table->string('department');
$table->string('designation');
$table->string('supervisor');
$table->string('hr_master');
$table->timestamps();
When the first time i logged in using JWT, i have emp_id from User is foreign key to Employee table. I want to view the profile of the employee using emp_id in table User to get the information of that employee in Employee table. This is the function i write
public function getEmployeeDetail(){
return $this->user->employee()
->first()->toArray();
}
in first create a relation in your User model
public function employee()
{
return $this->hasOne(Employee::class,'emp_id','id');
}
now for call it
$user=auth()->user();
$user->employee //out put = curent Employee detail
You can add an accessor to App/User model.
public function getEmployeeAttribute()
{
return \App\Employee::find($this->emp_id);
}
After that you can access the related App\Employee data like this:
$user->employee->employee_name
And you can use optional helper function to prevent causing an error if user not related to any employee:
optional($user->employee)->employee_name
I need to seed a relationship in Laravel, where each user has many devices
The User model
public function devices()
{
return $this->hasMany(Device::class);
}
The Device model
public function users()
{
return $this->belongsTo(User::class);
}
}
The device_user table
Schema::create('device_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('device_id')->unsigned()->index();
$table->foreign('device_id')->references('id')->on('devices')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
The seeder
factory(App\Device::class, 20)->create()->each(function(App\Device $device) {
$device->users()->attach([
rand(1,5),
rand(6,15),
rand(16,20),
]);
});
But, when I run the migration with seeder, I get this message
Call to undefined method Illuminate\Database\Query\Builder::attach()
Please, help
attach for many to many relationships, you don't need device_user table for one to many relationship, in one to many you should create a column with name user_id in device table and just it. after that you can insert data in device table with user_id. and get user relationship with
Device::user()->get();
I have 3 tables Users, Profiles, and Friends.
Users contains users, obviously.
Then I got the Profiles and Friends table (see below).
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->string('picture')->nullable();
$table->string('status')->nullable();
$table->string('text')->nullable();
$table->boolean('show_sex');
$table->boolean('show_dob');
$table->timestamps();
});
}
public function up()
{
Schema::create('friends', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id_sender')->unsigned();
$table->integer('user_id_receiver')->unsigned();
$table->foreign('user_id_sender')->references('id')->on('users');
$table->foreign('user_id_receiver')->references('id')->on('users');
$table->integer('status'); // 1 = friends, 2 = under validation
$table->timestamps();
});
}
As you can see, i created some foreign keys that relates to the Users table.
The Friends table contains all friendships between users (the status field will determine if the friendship is under validation or validated).
I have the default User model that comes with Laravel 5.2 and was wondering, how can I easely get all the friendships, that belongs to the signed user?
Could I use something like belongsTo() or something to easely get all friendrequests where the user_id_receiver field is the same as the signed users id? I didn't quiet understand the documentation for hasOne or belongsTo.. Would be nice if someone could clearify how it actually works.
Thanks in advance.
Yes, you should use One-to-one relation between User and Profile models and One-to-many relation between User and Friend models. Add this to both models - Friend and Profile:
public function user()
{
return $this->belongsTo('app\User');
}
And add this to User model:
public function profile()
{
return $this->hasOne('app\Profile');
}
public function friend()
{
return $this->hasMany('app\Friend');
}
And then you could use Eloquent to get data:
$signedUserId = Auth::user()->id;
$currentUserFriendRequests = Friend::where('user_id_receiver', $signedUserId)->get();
I hope this will be helpful.