Laravel Eloquent Fill Model with multiple items - laravel-5

I've created a step by step form that's filling a model with data, saving to a session and moving to the next step. Finally, at the final step, it will save all the data.
What I'm having issues with is I have a table that will need multiple entries. Something like:
$myValues=[
['user_id' => 3, 'genre_category_id'=> 5],
['user_id' => 7, 'genre_category_id'=> 2]
]
But doing this leads to an empty model when I try to print it out:
$myModel->fill($myValues);
Is there a way to fill with multiple items, or is there another efficient way to pass over this data to the final step where I can save it?
Thank you!

There is no way to do this with models.
You can do DB::table('table')->insert($myValues); if you don't need to use models.

Related

Delete multiple record in laravel-8 that pass through URL

Through Passing single integer value , specified data is deleted from database.I want to pass multiple value and to delete corresponding data in database.
what i want to?
Scenario is like that:
http://127.0.0.1:8000/dlt/15,16
i want to delete 15,15 record from database.Every time whenever i want to delete multiple record, i take above url and put value 1,3 or 3,4,5 or 6,7,8,9 after dlt
My web.php file
Route::get("/dlt/{id}",[MyController::class,"dtl"]);
MyController.php file where i specified function for delete operation
use App\Models\City;
function dlt($id){
}
How can i do that.
How to delete multiple records using Laravel Eloquent
I have tried to understand from this above stackoverflow question but i did not understand because complete deletion process was not there.
Thanks in advance.
It looks like you just want to delete an array of ID's, there is a method built in laravel to do this and it goes as follows:
City::destroy([1, 2, 3]);
Read more on it from: https://laravel.com/docs/9.x/eloquent#deleting-an-existing-model-by-its-primary-key
If you want to do it for a string you can follow this example:
$example = "1,2,2,2,3,3,3,4";
$results = array_unique(explode(',', $example));
City::destroy($results); //Here city is model name
Hopefully this will help you reach your goal

Laravel: how to change the data of all models?

Currently the system has a few dozen models, controllers and a few hundred routes.
When carrying out any query in the database, if a certain value is found during that query, I can transform this data into another value.
An example to facilitate understanding is, when performing the query and before presenting the result, a hashtag is found, that hashtag is replaced with another value.
In this example, the difficulty is not to change the value itself (str_replace()), but to be able to intercept any of the results of queries to the database, search for this "keyword" and replace it.
But this change is only visual, it is not replacing the data in the database.
Of course I can do this on each controller, but due to the quantity, I don't think anything is viable
I think I need to somehow be able to intercept all the results of any consultation with the database and make this substitution, but I have no idea if I should use Middleware or another Laravel resource, or even that should be done by a ServiceProvider.
You can achieve this using Laravel's Resources.
You could create a HashtagResource and run all model results through it prior to utilising the data which could then look for the hashtag and replace it within the content as described.
For example, inside of the newly generated resource that wraps around your query, ie HashtagResource::collection(MyModel::all())
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'content' => str_replace('#hashtag','#otherhashtag', $this->content)
];
}

Laravel Eloquent, difference between attach() and syncWithoutDetaching()

I'm wondering if there is a difference between the two following Eloquent instructions that update the data on the role_user pivot table of a many-to-many relationship between User and Role models.
// Attach the specified roles to the user
$user–>roles()–>attach([1, 2, 3]);
// Sync the specified roles without detaching the one previously assigned to the user
$user–>roles()–>syncWithoutDetaching([1, 2, 3]);
I think they do the same thing, am I correct?
"attach" method inserts the array argument without syncing or removing existing data while "syncWithoutDetaching" method updates the existing value comparing with array argument and also does not remove rest of the existing values.

when using laravel scout, searchable() isn't updating related models

I am having an issue getting related models to update with scout elastic search.
$event->priceranges()->delete();
$event->priceranges()->Create([
'price' => $ticket['ticket_price']
]);
$event->update([
'show_times' => $request->showtimes,
]);
$event->searchable();
In my database I see the event and price range tables update. However when I look at my elastic search data, only data on the event has been updated. Any related models are not updated.
If I make a second update to the model and price range model, then the elastic search data shows my data from the first update I made (it is always one update behind for related models)
I tried doing
$event->pricerange->searchable()
but gives me an error because I don't have a searchable index for pricerange, I am just using my event model and its relationship to index. Is there a way to force the update other than searchable()?
Looks like your relationship is being indexed in the Event model index, correct?
Probably it's not being updated because the relationships are already loaded, and Laravel doesn't update the relationship data that is already loaded, for example:
$event = Event::with('priceranges')->first()
var_dump($event->priceranges->count()): // outputs for example 5
$event->priceranges()->create([...]);
var_dump($event->priceranges->count()): // still outputs 5, meaning that the created pricerange is not loaded
So, to fix this issue you can reload the model before calling searchable():
$event = $event->fresh();
$event->searchable();
But, note that everytime you update, the searchable method is already being called, so you will be indexing it two times on every update.
So, alternatively you can update your toSearchableArray() method in Event model to get a fresh model before returning the data (I'm assuming that you are using the babenkoivan/scout-elasticsearch-driver).

Laravel get all related models for multiple models

I have a users table and a groups table.
I have set up a many to many users/groups relations.
When I run
$users = User::where("id",'=',6)->first()->groups;
,I get the right group.
But I will have cases where my queries will take in an array of users.
How do I get all the groups of all those users using laravel relationships ?
eMAD's suggestion does not work because Laravel only allows relationship functions to be execute on objects and not array of objects. What you want harvey is a concept called eager loading.
$users = User::whereIn('id', [6, 7, 8])->with('groups')->get();
By using this code, you will be able to access $user->groups->someInfo in your code. Happy coding

Resources