how to sync() method additional pivot table Laravel - laravel

i have pivot table call user_privilege,
user_id,
privilege_id
house_group_id,
i use method sync for store data into pivot tabl, this is my method
$data = $this->getCollectedData($getListCollectData, $viewType, $data);
$getData = $this->crud->store($data);
$getData->getPrivilege()->sync([
'user_id' => $getData->id,
'house_group_id' => $this->request->get('house_group_id'),
'privilege_id' => 3,
]);
this is my getPrivilege() method in Users Model
public function getPrivilege()
{
return $this->belongsToMany(Privilege::class, 'user_privilege', 'user_id', 'privilege_id', 'house_group_id');
}
but when i click submit, return error like this
SQLSTATE[HY000]: General error: 1364 Field 'house_group_id' doesn't have a default value (SQL: insert into `user_privilege` (`privilege_id`, `user_id`) values (b3f08343-a8f6-4a45-b7bc-b396125634d3, ?))
when i dd($this->request->get('house_group_id')) return ID house_group_id like this
"2539d741-1526-4c42-b57a-da60e2e862d8"
this is UUID from house_group_id,
Whats wrong in My Code, how to save data with addtional pivot table ?
thanks

Related

How to select specific column from parent and child in laravel

Please see my code below.
Controller
$orders = Order::with('product:id,name')
->select([
'id',
'order_number',
'ordered_on',
'status',
'total'
])
->where('customer_id', session('customer_id'))
->orderBy('ordered_on', 'DESC')
->paginate(6);
dd($orders);
Order model
public function product()
{
return $this->belongsTo(Product::class);
}
The result above returns null when you check the product relationship data.
What I need
Select specific columns from Order model, then select specific columns from product relationship.
You need to add the foreign key that you are referencing:
->select([
'product_id'
...
])
...
When using this feature, you should always include the id column and any relevant foreign key columns in the list of columns you wish to retrieve.
Docs: https://laravel.com/docs/9.x/eloquent-relationships#eager-loading-specific-columns

How to scope results with pivot table October Cms

The solution to this is probably easy and I'm just missing it, but I can't seem to figure out how to limit "customers" based on the "user" that the customer belongs to.
This is a many to many relationship, so a customer can belong to more than one user and a user can have more than one customer.
Here is my relationship definition:
public $belongsToMany = [
'user_id' => [
'RainLab\User\Models\User',
'table' => 'tablename_users_customers',
]
];
And here is the scope function that doesn't work as I'd expect:
public function scopeUser($query) {
$user = Auth::getUser()->id;
return $query->where('user_id', $user)->get();
}
Finally, here is my error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_id' in 'where clause' (SQL: select * from `tblcustomers` where `user_id` = 1)
Obviously, the error is because the "user_id" column doesn't exist in the 'tblcustomers' table, but rather in the pivot table. How can I use the "user_id" from the pivot table in my scope function? I need to only display Customers that belong to the currently logged in user.
Yes this can be possible
But First thing is you need to remove get() method from the scope, scope meant to return query object for chaining methods further.
Your relation and scope should look like this
// relation
public $belongsToMany = [
// PLEASE MAKE RELATION NAME CORRECT HERE
'users' => [ // not user_id, use `users`
'RainLab\User\Models\User',
'table' => 'tablename_users_customers',
// 'key' => 'customer_id', if needed
// 'otherKey' => 'user_id' if needed
]
];
// scope
use RainLab\User\Models\User;
public function scopeUser($query) {
return $query->whereHas('users', function($usersQuery) {
$user_id = Auth::getUser()->id;
return $usersQuery->where((new User)->getTable() . '.id', $user_id);
});
}
// usage
$result = Customer::user()->get();
dd($result);
// you will get only customers which has relation with current logged in user.
if any doubts please comment.

how to store data addtional column in pivot tavle laravel

i have pivot table like this
this is my Users model
public function getHousing()
{
return $this->belongsToMany(Housing::class, 'user_housing', 'user_id', 'housing_id')->withPivot('primary');
}
this is my Housing model
public function getUser()
{
return $this->belongsToMany(Users::class, 'user_housing', 'housing_id', 'user_id')->withPivot('primary');
}
i want to save primary with 1, this is my controller
$getData = $this->crud->show($id);
if (!$getData) {
return redirect()->route('admin.' . $this->route . '.index');
}
$data = $this->validate($this->request, [
'housing_group_id' => 'required',
'housing_id' => 'required',
'primary' => 'required',
]);
$getData->housing_id = $getData->getHousing()->pluck('id')->toArray();
$getData->getHousing()->sync($this->request->get('housing_id'), ['primary' => 1]);
$id = $getData->id;
i already add array fill primary 1, but i have error like this
SQLSTATE[HY000]: General error: 1364 Field 'primary' doesn't have a default value
how to save additional field in pivot table laravel ?
thanks
in sync with additional column in pivot table, you should pass an associative array for each id with column name as key and field value as value
$elements_array[$this->request->get('housing_id')]=['primary' => 1]
$getData->getHousing()->sync(elements_array);
if you have more than an 'id' to sync ... you must repeat the first step for each id.
check this:
https://stackoverflow.com/a/27230803/10573560

How to associate comments to users on Laravel?

public function store(Post $post)
{
$this->validate(request(), ['body' => 'required|min:2']);
$post->addComment(request('body'));
return back();
}
this is my code
I am having this error
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into comments (body, post_id, updated_at, created_at) values (ewrtyuttrew, 1, 2018-02-15 15:44:17, 2018-02-15 15:44:17))
You need to add a user who created the comment manually. For example:
public function addComment(string $body)
{
$this->comments()->create(['body' => $body, 'user_id' => auth()->id()]);
}
In your User model you can define the relationship as:
public function comments() {
return $this->hasMany(Comment::class);
}
So, if the user it's the logged user, then you can retrieve it with the Auth facade:
$user = Auth::user();
Then you can simply do:
$user->comments()->save(new Comment(request('body'));
Note that you must set the "fillable" fields on the Comment model in order to allow the dynamic creation.
Field 'user_id'
Open phpmyadmin and open comments table then after
Field 'user_id' => auto increment and primary key add
Try this I solve this type issues, thanks

How to update field in table Laravel or create?

I try to update field rate in table by primary key user_id.
So, I need to increment of decrement rate field. If row is not exist I need to create it.
I tried:
$this->point = -1; // Or $this->point = 1;
Rating::updateOrCreate(["user_id", $id], ["rate" => $this->point]);
But it does not work:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where clause' (SQL: select * from `rating` where (`0` = user_id and `1` = 5) limit 1)
This is because your passing the column and the value as two separate values.
Change:
["user_id", $id]
to:
["user_id" => $id]
Hope this helps!
Laravel (eloquent) provides a fluent way to update related models.
Assuming the following model structure:
Rating.php
public function user()
{
return $this->belongsTo('App\User');
}
User.php
public function ratings()
{
return $this->hasMany('App\Rating');
}
You can easily update the relation via associate()
$user = User::findOrFail($userId);
$rating = Rating::findOrFail($ratingId);
$rating->user()->associate($user)->save();
Read more about Relationships in Eloquent

Resources