I'm new to Laravel and here's my issue.
I have a table currentpercentage.
This is the structure of the table currentpercentage
currentpercentage(**id**, name, total_cap, current_usage, created_at, updated_at)
I'm trying to calculate percentage of current usage; based on total_cap and current usage.
total_cap = 1000,
current_usage = 237,
name = User Name
In my controller i've setup a query to get the value of total_cap and the value of current_usage then calculate that the percentage would be.
When i call my query, it returns an array with the column name (total_cap) and value (1000). Same as when i query for current_usage.
{
"currentpercentage": [
{
"total_cap": 1000
}
]
}
I just want the query to return just the number (1000) without the array.
This is my query
$totalcap = CurrentPercentageModel::select('total_cap')->where('name', '=', 'User Name')->get();
How do I just get the value. Or is there an easier way to calculate the percentage from one query?
CurrentPercentageModel //What I use to connect to the database. DB Model
The problem is that you are using the get method which returns a collection even when you only have one row.
$totalcap = CurrentPercentageModel::select('total_cap')->where('name', '=', 'User Name')->get();
If you just want one record and one column value, then use the value method to get just the value of the column, more info here (you might have to scroll a little bit)
$totalcap = CurrentPercentageModel::select('total_cap')->where('name', '=', 'User Name')->value('total_cap');
Related
I'm creating database notifications. I have 2 Notification classes:
InterviewRequestReceived.php:
$user = Auth::user();
$interviewRequestReceived = InterviewRequestsReceived::latest()->where('user_id', $user->id)->get();
return [
'date_time1' => $interviewRequestReceived[$interviewRequestReceived->count() - 1]->latest()->get('date_time1'),
'date_time2' => $interviewRequestReceived[$interviewRequestReceived->count() - 1]->latest()->get('date_time2')
];
and InterviewRequestSent.php:
public function toDatabase($notifiable)
{
$user = Auth::user();
$interviewRequestSent = InterviewRequestsSent::latest()->where('user_id', $user->id)->get();
return [
'date_time1' => $interviewRequestSent[$interviewRequestSent->count() - 1]->latest()->get('date_time1'),
'date_time2' => $interviewRequestSent[$interviewRequestSent->count() - 1]->latest()->get('date_time2')
];
}
I have 3 tables. interview_requests_receiveds, interview_requests_sents and I created the notifications table and migrated.
On my form I have 2 options for datetime fields, so Employers can choose 2 possible date and times that would work for them to interview a candidate.
My form is working.
My notifications are working except it's inserting all of the logged in Users' date and times, instead of just the last inserted record.
I'm trying to use latest(), but it's not working.
As per Laravel Documentation
The latest and oldest methods allow you to easily order results
by date. By default, result will be ordered by the created_at
column. Or, you may pass the column name that you wish to sort by
If you want to use latest then instead of get() use first() function:
If there is already created_at column in your table then
$interviewRequestSent = InterviewRequestsSent::latest()->where('user_id', $user->id)->first();
OR
Assuming you want to get last record based on id column
$interviewRequestSent = InterviewRequestsSent::latest('id')->where('user_id', $user->id)->first();
Or you can get the last record using any below methods
InterviewRequestsSent::where('user_id', $user->id)->last();
OR
InterviewRequestsSent::where('user_id', $user->id)->orderBy('id', 'desc')->first();`
Reference:
Laravel -> Query Builder -> latest method
Using Eloquent in Laravel,
To get the minimum value of a column this code works:
public function getLowestYearBook()
{
return CV_Outputs::min('book_publication_year');
}
But to get the higher value it doesn't work, i'm using 'max' instead of 'min'.
How to get the higher? Thanks!
--------------- Edit:
the problem is I have some rows with "Not defined" text in it, so sorting by desc it returns that row, because letters are "higher" than number.
I fixed it by doing this:
public function getHighestYearBook()
{
return CV_Outputs::all()
->where('book_publication_year', '<>', "Not defined")
->sortByDesc('book_publication_year')
->first()->book_publication_year;
}
You should check if the type/value is the same in all rows, because max should do the job. But try sorting them in descending order which means highest first and then get the first element like this:
CV_Outputs::all()
->where('book_publication_year', '!=', 'Not defined')
->sortByDesc('book_publication_year')
->first();
i want to get difference between two values. i get my last entered value in bill no and get difference with input value.
this is my controller function model
$restPaymentSales = DB::table('sales')
->select('rest_payment')
->where('bill_no', $request->input('bill_no'))
->orderBy('created_at', 'desc')
->first();
$payment = $request->input('payment');
$doubleVal = doubleval($payment);
and i wrote calculation like this
$restSales = $restPaymentSales->child['rest_payment'] - $doubleVal;
but it shows me this error
Trying to get property of non-object
my table row like this
rest_payment -> double(11,2)
how can i fix this issue. basically i want to get difference between table last value order by date and input value.
Update your calculation from:
$restSales = $restPaymentSales->child['rest_payment'] - $doubleVal;
TO
$restSales = $restPaymentSales->rest_payment - $doubleVal;
I have related items in my database. I selected all of items from database by related id:
$next_stock = $this->model->get()->where('part_id', $in_data['part_id'])->all();
and I collection of rows grouped by one specific id, like on the picture. All of them selected by "part_id":
Selection Of Items
Grouped By Same Id
Also with this line of code i can select one of the items from this collection:
$next_stock = $this->model->get()->where('id', $old_stock['id'])->where('part_id', $in_data['part_id'])->first();
But how can I select the following items after this one?
Or, how can I select second or third item from this collect?
I cannot just increase id number by one from first, because sometimes this item ids not following each other.
Having a collection, you can take a specific element in the position with a combination of take() and last().
$collection = $this->model->get()->where('part_id', $in_data['part_id'])->all();
$second = $collection->take(2)->last(); //if this doesnt work, do it in 2 steps
$third = $collection->take(3)->last(); //if this doesnt work, do it in 2 steps
If you don't have a collection, take directly from database like this
$second = $this->model
->where('part_id', $in_data['part_id'])
->skip(1)
->first();
If it doesn't work with first()
$collect = $this->model
->where('part_id', $in_data['part_id'])
->skip(1)
->take(1)
->get();
$second = $collect->first();
Edit
skip() and take() are actually part of the query builder, not eloquent model. So it won't work with Eloquent in Laravel 5.4
Try with
$collect = $this->model
->where('part_id', $in_data['part_id'])
->get(1); //For the second record, 0 being the first
If you aren't doing it yet, you should set your model's relationships.
E.g. If you use "one-to-many", Eloquent will automatically determine the proper foreign key column on the model for you.
$parts = App\Stock::find(1)->partId;
foreach ($parts as $part) {
//
}
I'm trying to retrieve single column from my table grades.
For that I have used following code in my controller:
public function verify($id,$sid)
{
$grade=Grade::all('annual')->whereLoose('id',$id);
return $grade;
}
Where, annual is column name. But it is returning empty set of array [].
all() takes a list of columns to load from the database. In your case, you're fetching only one column called annual, therefore filtering on id later on does not return results. Replace your code with the following and it should work:
$grade = Grade::all('id', 'annual')->whereLoose('id', $id);
Keep in mind that it will return a collection of objects, not a single object.
NOTE: you're always loading all Grade objects from the database which is not efficient and not necessary. You can simply fetch object with given id with the following code:
$grade = Grade::find($id); // fetch all columns
$grade = Grade::find($id, ['id', 'annual']); // fetch only selected columns
The code you are using is loading all rows from the grades table and filtering them in code. It is better to let your query do the filter work.
For the columns part, you can add the columns you need to the first() function of the query, like so:
public function verify($id,$sid)
{
$grade = Grade::where('id', $id)->first(['annual']);
return $grade->annual;
}