Insert/create data using belongsTo Relation in laravel - laravel

Phone BelongsTo User. Now how i insert phone & user data both through belongsTo Relationship & auto get user_id foreign key in phone table. Here I try this code but not work.
$phoneData = $request->get('phone');
$userData = $request->get('name');
$phone->user()->create($userData);
$phone->create($phoneData);
Here is in form input field

Something like this:
$userData = $request->get('name');
$phoneData = $request->get('phone');
$user = User::create($userData);
$user->phones()->save(new Phone($phoneData));
Of course you'll need to define the relationship on the User model as well:
// \App\User.php
public function phones()
{
return $this->hasMany(\App\Phone::class);
}

You can't create a phone without an user, it's not recommended because the foreign key constraint, that you must have in your database, won't let you..
$userData = $request->get('name');
$phoneData = $request->get('phone');
$phone = new Phone();
$phone->user()->associate(User::create($userData));
$phone->save();
Maybe you are looking for something like this...
for updating..
$phone = isset($phoneData['id'])
? Phone::where('id', $phoneData['id'])->first() : new Phone();
$phone->user()->associate(User::firstOrCreate(
['email' =>$userData['email']], .... extra data from user));
$phone->save();

Related

Eloquent is setting a value to null

i'm having an error with Eloquent (and Many to Many relationship).
This is my code:
$user = new Users;
$rs = $user
->company()
->where('company_role.users_id', $request->session()->get('usrid'))
->where('code', $request->company)
->first();
The query that Eloquent perform is this one:
select `companies`.*, `company_role`.`users_id` as `pivot_users_id`, `company_role`.`companies_id` as `pivot_companies_id`, `company_role`.`role_name` as `pivot_role_name` from `companies` inner join `company_role` on `companies`.`id` = `company_role`.`companies_id` where `company_role`.`users_id` is null and `company_role`.`users_id` = 1 and `code` = 12345678901 limit 1)"
How is this possible? Do you guys have any idea?
This is my Users model:
class Users extends Model
{
//table associated with model
protected $table = 'users';
protected $primaryKey = 'id';
public function company(){
return $this->belongsToMany('App\Companies','company_role')->withPivot('role_name');
}
}
It was a rookie error
i just changed this:
$rs = $user->company()->where('company_role.users_id',$request->session()->get('usrid'))->where('code',$request->company)->first();
into this:
$rs = $user->find($request->session()->get('usrid'))->company()->where('piva',$request->company)->first();
and everything works as expected.
Thanks to everyone!
First, define the variables
$user_id = $request->session()->get('usrid');
$user = User::find($user_id);
Then, you need to find the user and the companies they are attached, and an individual company with the search params
$companies = $user->company()->get();
$company = $user->company()->where('code', $request->company)->first();

Laravel MorphMany Relationship - What am I missing?

I have the defaults users table which I've altered to have userable_type and userable_id. I have various models, eg BursaryAdministrator and BursaryProvider and users can belong to either.
BA/BP Model:
public function users() {
return $this->morphMany('App\Users', 'userable');
}
Users Model:
public function userable()
{
return $this->morphTo();
}
During my migration, I've created a default BursaryAdministrator and BursaryProvider and a couple of users. I want to assign them to each:
$bp = \App\BursaryProvider::first();
$user = User::find(2);
$bp->users()->associate($user);
$ba = \App\BursaryAdministrator::first();
$user = User::find(3);
$ba->users()->associate($user);
However, they're not linking as the userable_type / userable_id fields are null. I've tried both 'associate' and 'attach'.
Whats the correct what to do this?
You could try to save() the user after association, i.e.:
$bp = \App\BursaryProvider::first();
$user = User::find(2);
$bp->users()->associate($user);
$user->save()
$ba = \App\BursaryAdministrator::first();
$user = User::find(3);
$ba->users()->associate($user);
$user->save()
Ok, so this was the correct way at the end of the day:
$bp = \App\BursaryProvider::first();
$user = User::find(2);
$user->userable()->associate($bp);
$user->save();
$ba = \App\BursaryAdministrator::first();
$user = User::find(3);
$user->userable()->associate($ba);
$user->save();
Thanks to #dparoli for pointing me in the right direction.

Update the Record of Related Model in Laravel

How to update a record in the related table model by chain expression?
This is what I currently do (and it works)
$user = User::find(1);
$token = Token::where('user_id', $user->id)->first();
$token->token = $request->token;
$token->save();
But can I do the above in a more elegant way, such as?
$user = User::find(1);
$user->token()->token = $new_token;
$user->token()->save();
My User Model
public function token()
{
return $this->hasOne('App\Token');
}
In one line:
User::find(1)->token()->update(['token' => $new_token]);
Just know these things before using it:
User find could return null if the user id is not found.
The saved and updated model events will not be fired for the updated models.
The update method execution does not go through the Eloquent model methods.
However in your particular case I think it's valid, specially if you know that the user id will always be valid.
Yo can do it like this :
User::find(1)->token()->update(['token' => $new_token]);
Or do it in youApp\Token class like this :
User::find(1)->token()->update_token($new_token);
And create update_token function in App\Token class:
public function update_token(string $new_token)
{
$this->update(['token'=>$new_token]);
}
$user = User::with('token')->findOrFail(1);
$user->token->update(['token' => $request->token]);

-Laravel 5.2 insert logged in users foreign key automatically into product table when creating product

i've been working on a CRUD system lately, what i want is that when a logged in user creates a product on my website his name will automatically be inserted as a foreign key into my product table.
this is my Product model i've made for it.
//inkoopprijs = sell price
//verkoop prijs = buy price
//naam = product name
protected $fillable = ['naam', 'inkoopprijs', 'verkoopprijs','users_id','created_at', 'updated_at'];
protected $table = "product";
this is my ProductController store function
public function store(Request $request)
{
$product = Product::create($request->only(['naam', 'inkoopprijs', 'verkoopprijs', 'users_id']));
return redirect(route('product.index'));
}
You can do this with Eloquent events like so:
Product::creating(function ($product) {
$user = auth()->user();
$product->users_id = $user->id;
});
You can access the current logged in user with Auth::user(); or auth()->user();
We can also access the identifier with Auth::id();
Product::create([
'naam' => $request->get('naam'),
'inkoopprijs' => $request->get('inkoopprijs'),
'verkoopprijs' => $request->get('verkoopprijs'),
'users_id' => \Auth::id()
]);
I hope this is what you meant.
You can use users id as hidden field in the form but need to consider the security aspects of using users id in the form. It depends on where you are using. May be you can use this method is the user is already authenticated.
<input type="hidden" name="users_id" value="{{Auth::user()->id}}">

Laravel 5 Eloquent, double one-to-one save (get Id before save)

$profile = new Profile;
$user = new User;
$user['profile_id'] = $profile['id'];
$profile['user_id'] = $user['id'];
$profile->save();
$user->save();
So I have the relationships setup using "hasOne" in both Models files. These are NOT NULL FOREIGN KEYS so I need to define the id relationship immediately. But ['id'] is not available until after save. How can I do these 2 save operations at the same time?
You should have the foreign key in only one of the tables, and define the other relationship as belongsTo
EDIT
If you keep the user_id in the profiles table, then add this to your user model
public function profile()
{
return $this->hasOne('App\Profile');
}
then you can do this
$user = new User;
$user->save();
$user->profile()->save(new Profile());

Resources