How to scope results with pivot table October Cms - laravel

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.

Related

How do I return the ID field in a related table in Laravel request

I have two related tables and I want to return all fields including the ID (key) field. My query below returns all fields except the ID. how do I return the ID field from one of the tables?
'programmes' => ProgrammeInstances::with('programmes')->get(),
the query below returns Unknown column 'programmes.programme_title' as it is looking for it in the table 'programme_instances'
'programmes' => ProgrammeInstances::with('programmes')->select('programmes.programme_title', 'programmeInstances.id', 'programmeInstances.name', 'programmeInstances.year')->get(),
Laravel provides multiple relationships, one of these is the hasMany() relationship which should return a collection where a User hasMany rows inside of your database
For example, inside your User model :
public function programmes() {
return $this->hasMany(Program::class);
}
Now in your controller, you can do :
public function edit($id) {
$programmes = User::find($id)->with('programmes')->get();
return view('user.edit')->with('programmes', $programmes);
}
And then you can loop over it inside your view
#forelse($programmes->programmes as $program)
// provide the data
#empty
// the user doesn’t have any programmes
#endforelse
a solution i found below - still not sure why ID isnt automatically returned when i get all fields, but works when i specify individual fields:
'programmes' => ProgrammeInstances::with('programmes')
->get()
->transform(fn ($prog) => [
'programme_title' => $prog->programmes->programme_title,
'id' => $prog->id,
'name' => $prog->name,
'year' => $prog->year,
]),

how to sync() method additional pivot table 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

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

Laravel - Table with two columns, each has ID from different tables

I need to create a single objective that has a multi-select drop down wherein different departments can share that same objective. I wanted to create a relationship table with an output like this.
Department Table
id | name
1 Science Department
2 Math Department
3 Biology Department
Objective Table
id | name
1 Be the best
Relationship Table
objective_id | department_id
1 1
1 2
1 3
This is what I think of inside the controller.
public function store(Request $request) {
$objective = Objective::updateOrCreate(
[ 'id' => $request->id ?? null ],
[ 'name' => $request->name ]
);
// From multiple select drop down
foreach($request->departments as $department) {
RelationshipTable::updateOrCreate(
[ // what should be the case? ],
[
'objective_id' => $objective->id,
'department_id' => $department['id'],
]
);
}
}
I'm not sure on how I would define this in the Model and how I could call their relationship inside the resource. I even think that my controller is wrong or are there better ways to achieve this?
First You are running query under loop is a very bad process.. may this process will help u? change it as your need!
public function store(Request $request) {
$objective = Objective::updateOrCreate(
[
'id' => $request->id ?? null,
'name' => $request->name
]
);
// From multiple select drop down
$insert_array = [];
foreach($request->departments as $department) {
array_push($insert_array,[
'objective_id' => $objective->id,
'department_id' => $department['id'],
]);
}
RelationshipTable::updateOrCreate($insert_array);
}
//Relationship Should Be Like in this example
Relationship Model
public function object() {
return $this->hasOne('Model Class of Object' , 'objective_id ' , 'id')
}
public function depertment() {
return $this->hasMany('Model Class of depertment' , 'department_id' , 'id')
}

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

Resources