I'm trying to create multi selection bootstrap output to save in database but I'm getting an array in my controller like ["6","7"]. How I can save this?
There is 2 selection that means 2 row must created.
The query I was trying:
$table = Pool_user::updateOrInsert(['pool_id' => [$string1], 'user_id' => $request['id']]);
Can anyone help me to solve this?
By responding directly to your question, you need to create an array of arrays with the values you want to enter.
Something like this:
$array = [];
foreach($request['pool_ids'] as $pool_id){ //$request['pool_ids'] -> ["6","7"]
array_push($array, [
'pool_id' => $pool_id,
'user_id' => $request['id']
]);
}
$table = Pool_user::insert($array);
However, considering that Pool_user is a Pivot table of a Many to Many relationship, there is a much better method of doing this.
Let's say in User Model, have a relationship called polls().
You can simply ask the Eloquent to synchronize the relationships:
$user = User::find($request['id']);
$user->polls()->sync($request['pool_ids']); //$request['pool_ids'] -> ["6","7"]
Hope this helps
Related
I have inherited a project that has a a few CRUD forms ... On the create form we need to create entries for a hasMany and belongsToMany relationship. So basically what i have got is the following
$movie = Movie::create($request->validated());
// Then to save the belongsToMany
foreach ($request['actors'] as $actor) {
// do some data manipulation
$actor = Actor::where('code', $actor->code)->first();
$movie->actors()->attach($actor);
}
// Save the hasMany
foreach ($request['comments'] as $comment) {
// do some data manipulation
$movie->comments()->create([
'title' => $comment['title'],
'body' => $comment['body'],
]);
}
I'm not sure if this is the best way of doing this, but it seems to work.
The problem I am having is that in the edit form, these actors / comments can be edited, added to or deleted and i am unsure of how to go about updating them. Is it possible to update them, or would it be better to delete the existing relationship data and re-add them?
I have never updated relationships, only added them so i am unsure how to even start.
Any help would be greatly appreciated.
As laravel doc suggested you can use saveMany() method for storing relationship instances.
// Save the hasMany
foreach ($request['comments'] as $comment) {
$comments[] = [
new Comment([
'title' => $comment['title'],
'body' => $comment['body'],
]);
];
}
!empty($comments) && $movie->comments()->saveMany($comments);
For deletion and update you should define two routes, one for updating comment and one for deleting comment.
Route::patch('movie/{movie}/comment/{comment}',[MovieController::class,'updateComment']);
Route::delete('movie/{movie}/comment/{comment}',[MovieController::class,'deleteComment']);
This question already has answers here:
How to update a pivot table using Eloquent in laravel 5
(5 answers)
Closed 5 years ago.
I have a tables peoples countries and a pivot table country_people. The pivot tables has got attributes countries_id peoples_id number. I am able to get the foreign keys into the pivot table but i can't insert into number. How do i do this ?
People model
public function countries()
{
return $this->belongsToMany('App\Country')->withPivot('number')
->withTimestamps();
}
Country model
public function peoples()
{
return $this->belongsToMany('App\People')->withPivot('number')
->withTimestamps();
}
Controller
$people = new People(array(
'quantity' => $request->get('quantity'),
));
$people->save();
$order->countries()->sync($request->get('id')->attach('quantity'));
It looks like you're combining update methods. Check out https://laravel.com/docs/5.5/eloquent-relationships#updating-many-to-many-relationships for more details.
In your case, try:
$order->countries()->attach($request->get('id'), ['number' =>
$peoples['quantity']);
If you want to sync, instead of attach, use:
$order->countries()->sync([$request->get('id') => ['number' =>
$peoples['quantity']]);
If you want to attach additional columns to the pivot table, you can pass it in through as array. For example:
$id = intval($request->get('id'));
$order->countries()->sync( $id => ['number' => $quantity]); //assuming you have saved the value of number in quantity
Take a look at https://laravel.com/docs/5.5/eloquent-relationships under syncing associations for more details.
Also, keep in mind that using sync will remove any of the previous relationships if they are not specified in the array. Use syncWithoutDetaching if you don't want this to happen.
I have a table where i have user_id and role_id in it. Now if I select user_id =1 from dropdown and role_id = 2 from dropdown and save it ..Next time if I want to set same user another role instead of creating new row in table..How to update it without creating new one? can anyone suggest something?
$roleUser = RoleUser::firstOrNew(
['role_id' => $request->Input(['role_id']),
'user_id' =>$request->Input(['user_id'])] );
$roleUser->save();
I used the firstOrNew method but it creates a new entry instead of updating the old one.
I'm using this source code when Update or Create new record. Worked well with Laravel 5.2
If exist one record have user_id == your user_id => Will update role_id
Else will insert one more record for your user_id
$roleUser = RoleUser::updateOrCreate([
'user_id' => $request['user_id'],
],
[
'role_id' => $request['role_id'],
]);
Here is a code that should work. However, I don't quite understand your database architecture choice. If a user can only have one role, why don't you define a role_id in your users table, and then use a belongsTo relationship?
$role_user = RoleUser::where('role_id',$request->get('role_id'))
->where('user_id',$request->get('user_id'))
->first();
if (is_null($role_user)) {
RoleUser::create([
'user_id' => $request->get('user_id'),
'role_id' => $request->get('role_id')
])
}
so where's the issue here?
you are using firstOrNew method , which is similar to firstOrCreate typically do the following:
Select from the database
and if not exists
insert the given data
in case of using firstOrNew , you will need to ->save() to execute the query .
so it will not update your data if exists .
however, I think that you are looking for updateOrCreate method, which is take two array arguments , the first is the inserted data , and if exists the function takes the two array argument to update your row.
You may also come across situations where you want to update an
existing model or create a new model if none exists. Laravel provides
an updateOrCreate method to do this in one step. Like the
firstOrCreate method, updateOrCreate persists the model, so there's no
need to call save():
$roleUser = RoleUser::updateOrCreate(
// if not exists, insert the following RoleUser data
['role_id' => $request->Input(['role_id']),'user_id' =>$request->Input(['user_id'])],
// otherwise, update RoleUser set role_id = ?
['role_id' => $request->Input(['role_id'])]
);
$roleUser = RoleUser::firstOrNew(array('role_id' => Input::get('role_id')));
$roleUser ->save();
you can add multiple fields..
example..
If there's a flight from Oakland to San Diego, set the price to $99.
If no matching model exists, create one.
$flight = App\Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99]
);
`
I have three tables (simplified) which are:
And I have to display all houses for each user.
In my controller I have a function like this:
public function create_houses_table($usr_id)
{
$crud = new grocery_CRUD();
$crud->set_language("italian");
$crud->set_theme('datatables');
$crud->set_subject('Casette');
$crud->set_table('tbl_houses');
$crud->set_relation_n_n('Casette',
'tbl_users_houses',
'tbl_users',
'house_id',
'user_id',
'usr_name',
NULL,
array('user_id' => $usr_id));
...
}
and what I get is this:
Every time I select a user from the combo I need to refresh my list filtering on usr_id...but I get always all the houses.
What I'm wrong?
This is not the intended usage for set_relation_n_n (it will show all the user houses in one field inside the user row).
What you want can be better done listing from tbl_users_houses, filtering by client with $crud->where() and linking with the other tables with two simple relations.
If I understand correctly you are trying to fetch only the records for the logged in User... and u have multiple users per house, hence the n-n relation.
I also faced this problem and here's what I did.
$myprojects = $this->admin_model->get_employee_projects($this->user_id);
$myprojectids = array_column($myprojects, 'id');
//get only one column from the multi-dimensional array
$crud->where("`projects`.id IN", "(" . implode(",", $myprojectids) . ")", false);
// the false disables escaping
$crud->set_relation_n_n('assigned_employees', 'project_employees', 'employees', 'project', 'employee', 'name');
//Only so it also still shows the name of Users assigned
So basically projects here is like houses, and I am using the WHERE IN clause to filter the records based on the projects I get from my model method...
I have the following basic schema:
players
id
name
profiles
id
player_id
email
subsets
id
profile_id
alias
I was under the impression the following operation was possible when creating a new record:
Player::create([
'name' => 'Player 1',
'profile.email' => 'player1#email.com',
'profile.subset.alias' => 'Player 1 alias'
]);
Since this code doesn't seem to work, is there anyway to save relationships records together with the create method?
Basically, you can't do this as easy as it looks.
In the docs, all related models are created after the base model is created
$profile = new Profile(array('email' => 'player1#email.com','alias'=>'Player 1 alias'));
$player = new Player(array('name'=>'Player 1'));
$player = $post->profile()->save($profile);
However , if you really want to do it in one go, you can overwrite the save() method in the Player model :
public function save(){
Database::transaction(function() {
$profileModel = new Profile($this->profile);
parent::save();
$this->profile()->insert($profileModel);
});
}
You will then pass the array to the Player method like :
array(
name='Player name',
profile=>array(
email=>'player1#email.com',
subset=>array(
alias=>'Player 1 alias'
)
);
Although this is not a recommended action.
Please read more about how to save the Eloquent models and relationships :
Tutorial 1
Tutorial 2
Everywhere is suggested to create the base model first, then the related models.