How to Use Where Query Builder in Laravel> - php

I've a Laravel Application but being more straight forward!
How to use where query, i want to get all the data of table where email is current auth()->user()->email.
I've used a submitter column where i post the email of who is posting the data.
Currently i'm trying like this:
#foreach (\App\Models\InsertFormModel::all()->where('submitter', value: strtolower(auth()->user()->email)) as $formData)

I think it's enough like this
$email = strtolower( auth()->user()->email );
$get_data = \App\Models\InsertFormModel::where('submitter',$email)->get();

If I understand correct it seems you are trying to using where clause on Collection (which also has a method called where but for filter data on its items) because all() method will fetch all records in your table in database and put into a Collection object. You could try this
#foreach (\App\Models\InsertFormModel::where(('submitter', strtolower(auth()->user()->email))->get() as $formData)

Related

is that possible to get data once and the perfrorm query on that instead of database in laravel?

Is that possible to get data at once and then perform query on it instead of database. Because I am doing calculation for almost 500 customers. for while i need to run almost 100 queries for each customer in database with same pattern , that why i am asking that if I can get data at once and then perform query on that data instead of database. because each time for each customer increase mysql cpu consumption
What i am doing right now
foreach($customers as $customer)
{
$customer_charge= CustomerCharge::where('customer_id',$customer->id)->with('rate_charge')->with('chilled_rate_card')-->with('frozen_rate_card')->get()
$this->calculateConsignment($customer_charge);
}
I want to do like that
$customer_charge= CustomerCharge::whereIn('customer_id',[array])->with('rate_charge')->with('chilled_rate_card')-->with('frozen_rate_card')->get()
Now find() here customer charge form $customer_charge object instead of database
Is that possible if yes then how?
Is that possible ?
Yes.
When you perform a query, Laravel returns to you an Eloquent Collection which allows on which you can still call the same methods to retrieve a specific data:
$customer_ids = $customers->pluck('id'); // Assuming $customers is an Eloquent Collection
$charges = CustomerCharge::whereIn('customer_id', $customer_ids)
->with('rate_charge')
->with('chilled_rate_card')
->with('frozen_rate_card')
->get();
foreach($customers as $customer)
{
$customer_charge = $charges->where('customer_id', $customer->id)->first(); // querying the already retrieved $charges data, not the database
$this->calculateConsignment($customer_charge);
}

laravel update and select

I have a situation to update the row based on id and return the complete row. I can do it in two queries but i want to do it in one query only. I have write this...
$result= DB::table($this->table)
->whereRaw($where['rawQuery'], $where['bindParams'] ? $where['bindParams'] : array())
->increment($updateField);
if($result){
return DB::table($updateTable)
->select('id')
->where('campaign_id',$where['bindParams'])
->where('date',date("Y-m-d"))
->get();
}else{
throw Exception("Error in fetching data");
}
I copied this from what you commented in your question:
No i want to return the id of the updated row or complete row if possible
If you want to return the ID of the just updated 'row' you're talking about. You can use Eloquent to accomplish this.
You can use a route like this:
Route::put('demo/{id}', Controller#update);
Then in your update function in your controller you can get the ID.
Find the model with $model = Model::find(id);
do things with the data you get.
Like $model->name = Input::get('name');
Then use $model->save();
After saving you can do $model->id;
Now you get back the ID about the row you just updated.
Refer back to this question:
Laravel, get last insert id using Eloquent
But any way it'll always be at least 2 queries (a SELECT and an UPDATE in MySQL, however you do it)
You can check Laravel Eloquent if you want a "cleaner" way to to this.

is there a way to get the list of id from result of pagination() in laravel?

To do pagination in laravel, the easiest way is by:
$items = ModelOfItem::orderBy('my_order_field', 'asc')->paginate(10);
However, in this pagination, I need to relate data from another table to this page. Currently, I do it by:
$item_ids = ModelOfItem::orderBy('my_order_field', 'asc')->take(10)->list('id');
$related_items = ModelOfRelatedItem::whereIn($item_ids)->get();
However, it needs to query database twice on data that I already have in hand, and it is painful to handle page after first page. Is there a way I can get a list of id from the pagination result so I can use to directly query on the second table?
P.S. It is an old project so it is still using Laravel 4.2.
Why don't you use joins? You can join the tables & call ->paginate(10) as the end method. if you still want this approach for whatsoever reason.. You can call ->lists('id') on paginator object as well.. like this:
$items = ModelOfItem::orderBy('my_order_field', 'asc')->paginate(10);
$item_ids = $items->lists('id');
$related_items = ModelOfRelatedItem::whereIn($item_ids)->get();

Eloquent - Updating all models in a collection

I want to set a certain attribute in all the models of a collection.
in plain SQL:
UPDATE table SET att = 'foo' WHERE id in (1,2,3)
the code i have:
$models = MyModel::findMany([1,2,3]);
$models->update(['att'=>'foo']);
taken from here
but doesn't work. I'm getting
Call to undefined method Illuminate\Database\Eloquent\Collection::update()
the only way i have found it's building a query with the query builder but i'd rather avoid that.
You are returning a collection, not keeping the query open to update. Like your example is doing.
$models = MyModel::whereIn('id',[1,2,3]);
$models->update(['att'=>'foo']);
whereIn will query a column in your case id, the second parameter is an array of the ids you want to return, but will not execute the query. The findMany you were using was executing it thus returning a Collection of models.
If you need to get the model to use for something else you can do $collection = $models->get(); and it will return a collection of the models.
If you do not just simply write it on one line like so;
MyModel::whereIn('id',[1,2,3])->update(['att'=>'foo']);
Another option which i do not recommend is using the following;
$models = MyModel::findMany([1,2,3]);
$models->each(function ($item){
$item->update(['att'=>'foo']);
});
This will loop over all the items in the collection and update them individually. But I recommend the whereIn method.
The best solution in one single query is still:
MyModel::whereIn('id',[1,2,3])->update(['att'=>'foo']);
If you already have a collection of models and you want to do a direct update you can use modelKeys() method. Consider that after making this update your $models collection remains outdated and you may need to refresh it:
MyModel::whereIn('id', $models->modelKeys())->update(['att'=>'foo']);
$models = MyModel::findMany($models->modelKeys());
The next example I will not recommend because for every item of your $models collection a new extra query is performed:
$models->each(function ($item) {
$item->update(['att'=>'foo']);
});
or simpler, from Laravel 5.4 you can do $models->each->update(['att'=>'foo']);
However, the last example (and only the last) is good when you want to trigger some model events like saving, saved, updating, updated. Other presented solutions are touching direct the database but models are not waked up.
Just use the following:
MyModel::query()->update([
"att" => "foo"
]);
Be mindful that batch updating models won't fire callback updating and updated events. If you need those to be fired, you have to execute each update separately, for example like so (assuming $models is a collection of models):
$models->each(fn($model) => $model->update(['att'=>'foo']) );

Populating a dropdown menu with database results in Laravel 4

I'm trying to populate a drop down menu with database results in Laravel 4. I'm extremely new to Laravel. This is actually my first site and I'm learning as I go. So, please tell me if I'm using the wrong terminology or not enough information.
I've got a database of company info and I need users to be able to choose a company from a dropdown. Or if the company isn't in the database to add it.
For the select menu, it needs to go like this:
[company name result]
And I'm using this code in my controller:
$companies = RecordCompany::get();
$company_selector = array();
foreach($companies as $company) {
$company_selector[$company->id] = $company->id;
$company_selector[$company->company_name] = $company->company_name;
}
return View::make('admin.record_new', array('company_selector' => $company_selector));
And this is what I've got in my view:
#if(count($client_selector)>0)
{{ Form::select('company_id', $company_selector, array_values($company_selector)[0]) }}
#endif
Disclaimer: I found this code online.
First, I don't understand how it will populate the value and option text without my telling it where to put the data.
Second, the error that's coming back is unexpected . When I take out the [0] in the form code, it tells me that $company_selector is undefined.
What am I doing wrong here?
In order to populate a dropdown menu with all the records from the RecordCompany model, you can do the following, in your view:
{{ Form::select('company_id', RecordCompany::lists('company_name', 'id')) }}
Note: In Laravel 5, the method lists has been deprecated. Use
pluck instead.
Explanation of the code:
The Form::select methods creates a HTML select tag.
company_id is the name of the select tag.
The second parameter is the options for the select tag. The lists method in any model (RecordCompany in this case) generates an associative array containing the parameters passed to that method (id and company_name in this case) of all the records in the model's database table.
If you want, you can also call the lists method from the controller and then pass the value to the view, like following:
In Controller
$company_lists = RecordCompany::lists('company_name', 'id');
return View::make('admin.record_new', array('company_lists' => $company_lists));
In View
{{ Form::select('company_id', $company_lists) }}
You can view the Laravel 4 documentation for generating a drop down list here: http://laravel.com/docs/html#drop-down-lists
I'm severelly against using DB calls in views. And here is why:
It ain't made for that!.
Period.
If I where you (note the if clause) I'd like better to fulfill a regular array, being the company->id the array key and any other information you may wanna for that especific key as a value. On my blade code, I'd made that way:
{{ Form::select('company_id', $companies) }}
Where "companies" would be a array passed as argument to the view by the controller.
Views aren't made to make DB consults. They are made to display data. JUST IT!
That being said:
The first argument on the Form::select is the selector's name. The one you get on the Input::get.
The second argument is the list for fulfill the select attribute (we already talked about it up there!)
And the third, non less important, is where you say which one comes selected on loading page (used for editions). You have to reference the identifier (the company id, in that case). It's optional, for obvious reasons.
If I didn't made myself clear, please ask down here! =D
For Laravel 5, you can code like this :-
Controller Code
$company_lists = RecordCompany::pluck('company_name', 'id');
return View::make('admin.record_new', $company_lists);
View Code
{{ Form::select('company_id', $company_lists) }}

Categories