Laravel Eloquent - Inserting multiple records - laravel

How do we insert multiple records using eloquent in Laravel?
Basically this:
Teacher::create([
'user_id' => $user->id,
'college_id' => $collegeId,
'first_name' => $this->faker->firstName(),
'last_name' => $this->faker->lastName()
],[...],[...]);

Okay, I just came across the github request where Taylor replied that it is not possible with Eloquent and to use Query builder instead.
Here is the link to the issue:
https://github.com/laravel/framework/issues/1295

Related

Laravel return error on duplicate column in CSV using maatwebsite/excel

I have code which i am using to import a CSV using the maatwebsite/excel package in Laravel.
I am importing to a collection, but before that i am using the rules method to run some validation.
I have the following validation rule to check the DB for user id's that already exist.
'user_id' => ['required', 'unique:user,id', 'string', 'max:60'],
But I also want to check that the same user id does not appear multiple times in the same column of the actual CSV file.
Is this possible?
Use it like this:
'user_id' => ['required', 'unique:your_csv_table_name,user_id', 'string', 'max:60'],
I use updateOrCreate function to avoid duplicate records https://laravel.com/docs/9.x/eloquent#upserts
$flight = Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99, 'discounted' => 1]
);

Update many in Laravel for one-to-many relationship

I have a one-to-many relationship in laravel. Author to Books. How would I update all records in specific book and remove those that are not in my array. For example, $book is array with author, page, publication and I want to update those records and at the same time detach those that are not there?
I used $book->update($array) but that failed. I also used sync and that failed because it can only be used with many-to-many
Here is some example of how to update many records in the model using where conditions.
Book::where('author', $author_name)
->update([
'price' => 10000, // Add as many as you need
]);
Book::where('author',$author)
->where('publication', $publication)
->update([
'price' => 10000,
]);
// Or More Dynamic
Book::whereAuhorAndPublication( $author_name, $publication )
->update([
'price' => 10000,
]);
it would be nice if you share an example of data and request data.

Optimize ApiResource

I'm having some problems when returning ApiResources because I can't figure out how to avoid overloading relationships.
In my UserResource, for example, I have:
<?php
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'role_id' => $this->role_id,
'role' => new RoleResource($this->whenLoaded('role')),
'group_ids' => $this->groups->pluck('id')->toArray(), // here are the problems
'groups' => GroupResource::collection($this->whenLoaded('groups')),
];
When loading single relationship id, all is ok, because $this->role_id is a property that is already in the Model. When using $this->whenLoaded('role') It will load the relationship conditionally, that's great!
The Problem: When loading many-to-many relationships, I can't set this 'conditional' eager load.
When I place:
'groups' => GroupResource::collection($this->whenLoaded('groups'))
It will load the ManyToMany Relation conditionally, cool!
BUT I would like to have array of ids with:
'group_ids' => $this->groups->pluck('id')->toArray()
However, this will execute the relation load ALWAYS

Laravel Collective - Model binding issue for non eloquent table names

I have a User model that has to have a table named admin_users, which is already stipulated in the model (protected $table = 'admin_users';)
I am using Laravel Collective form as follows:
{!! Form::model($user, ['route' => ['users.update', $user->id], 'method' => 'put']) !!}
My validation as follows:
$rules = array(
'first_name' => 'required',
'last_name' => 'required',
'email' => 'email|max:255|unique:users',
'country_id' => 'required|numeric',
'user_status' => 'required'
);
The only reason I am using Laravel Collective FORM::model for the ease of getting the request input back when validation fails:
(return redirect()->back()->withErrors($validator)->withInput($request->all())
On validation success though I am getting:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'crm.users' doesn't exist (SQL: select count(*) as aggregate from `users` where `email` = jocelyn33#example.com)
The weird thing is that it's not taking the table from User class table.
My question is if there is a way to have FORM::model get admin_users table name rather than users, and if I decide to let go of FORM::model and use FORM::open, would I still be able to get back request inputs of a failed validation?
Your validation rules are defining what table to use for a unique check:
'email' => 'email|max:255|unique:users',
unique:users is telling the unique rule to use the users table.
unique:table,column,except,idColumn -
Laravel Docs 5.6 - Validation - Unique Rule

Elasticsearch searching in different results

Im using Elasticsearch with laravel and Elasticquent https://github.com/elasticquent/Elasticquent over the Eloquent model.
Each user of my project can search in a different result of objects.
I have for example
$user_books->addToIndex();
Books::search($search);
And the problem is that everytime when someone go to the current step the elasticsearch is filled with his results.And at the end I have a combined result for each user with their books together.. which is a problem.
I need one user to search only into his results.
How can I achieve that? I think that I probably must delete the indexes after search because I dont need them anymore.
And then
There is no need to delete your indexes,
instead you should index the books added by users by building a custom index
of their user_id like this :-
$data = [
'body' => [
'book' => '$book->name',
'user_id' => Auth::user()->id,
],
'index' => 'your application name',
'type' => 'books',
'id' => $book->id,
];
and then you can use custom queries to search for book belonging to that user only like this
$books = Book::searchByQuery(array('match' => array('user_id' => Auth::user()->id)));
Refer to Query based search and Indexing and Mapping section here

Resources