Eloquent Get higher value of a specific table's column - php

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();

Related

using a number in laravel query builder where statement returns correct response but wrong response when variable containing a number is used

I am generating a query based on available parameters from the view. But when i add the $request parameters to the query it still returns all rows
This is a laravel 5.6 project. When I use an actual number, say 1, in my where clause directly I get a correct result but when I use the request variable it returns a wrong result
//This is the query variable
$all_students = DB::table('student_reports')
->leftJoin('students', 'student_reports.student_id', '=', 'students.id')
->leftJoin('classes', 'student_reports.class_id', '=', 'classes.id')
->when($request->has('class_id'), function($data) use ($request){
return $data->where('student_reports.class_id', $request->class_id);
});
//The condition for when returns true and the value for $request->class_id is a number
but when I do
->where('student_reports.class_id', 2)
I get a correct result
try, maybe help this
$classId= $request->input('class_id');
->when($classId, function($data, $classId) {
return $data->where('student_reports.class_id', $classId);
});

Laravel transform not working as intended on collection

I have a collection which is an eloquent query.
There is one column where I want to replace the value with another value.
I am using the transform function to do this however it is not working as intended.
Here is my query in the controller :
$articles = KnowledgeBaseArticle::getArticlesByDepartment($department)
->get()
->transform(function ($article) {
$article->category_id = KnowledgeBaseCategory::find($article->category_id)->name;
});
And the getArticlesByDepartment query from the model:
public function scopeGetArticlesByDepartment($query, $department){
return $query->where('department', $department)
->select('title', 'updated_at', 'department', 'id', 'category_id')
->orderBy('title', 'asc');
}
I want to return it so that all the rows with column category_id is replaced with the category name. You can see I am trying to do this by using $article->category_id by using find on the KnowledgeBaseCategory model to retrieve this. However this is not working at all and when I die and dump, I get an single column array full of nulls.
When I have died and dumped $article->category_id & find query inside the transform, it is returning the correct category name, it is just not replacing the category_id column with the category name.
I have also tried map instead of transform and got the same result.
If it matters, I am later on converting this data into JSON.
Where am I going wrong?
Transform, not unlike map, needs you to return the modified item of the collection, as this will replace the existing item.
transform(function ($article) {
$article->category_id = KnowledgeBaseCategory::find($article->category_id)->name;
return $article;
});
Since objects are mutable and passed by reference, you can just do this in an each() closure instead to save a line:
each(function ($article) {
$article->category_id = KnowledgeBaseCategory::find($article->category_id)->name;
});
Though, you really should have a relationship set up for category. There's no reason to be performing this find logic in your controller.

Check if record exist and return a boolean and compare it with inputs from a form

Hi i am having troubles sorting this out as the title says i am trying to check if a record exist and return a boolean instead of the record value from the database so i can compare it with a filter form, i know this can be solved using nested if's but i'm trying to find a better way, this is my code so far
public function getSend(){
if($this->request->role==1){
$id= Cv::select('cv.user_id','cv.pub')
->where('cv.pub','==',$this->request->pub)
->get();
dd($id);
return view('gestione.'.$this->view_namespace.'.send.pagina');
}
my idea is something like this
->where('cv.pub','==',$this->request->pub)
this one works because "pub" stores a boolean record in my database alot of other records store strings for example
->where('cv.something','==',$this->request->something)
wouldnt work because "something" is a string and not a boolean so how do i turn "something" into a boolean based on if wheter exist or not
thanks in advance by the way i am using laravel 5.1
Try this,
->where('cv.something','==',!empty($this->request->something))
$something = !empty($this->request->something);
if($something) {
$exits = Cv::where('cv.'+$something, $something)->get();
if($exits) {
// Cv exits
}
}
You may try something like this:
$id = Cv::select('cv.user_id','cv.pub') // select is not required here
->where('cv.pub','==',$this->request->pub)
->exists();
Also, you may use it like:
if (Cv::where('cv.pub', $this->request->pub)->exists()) {
// The record exists, so do something...
}
This query will return a boolean true if exists, otherwise false. You may also make the query conditionally depending on the $this->request->pub in one go, for example:
$exists = Cv::when($this->request->pub, function($query) {
$query->where('cv.pub', $this->request->pub);
})->exists();
if ($exists) {
// ...
}
$result = Cv::select('cv.user_id','cv.pub')
->where('cv.pub','==',$this->request->pub);
if($request->something){
$result = $result->whereNotNull('cv.something'); // or != '', depending how you store it
}
This is mostly how filters works
If you want to return a boolean you can use count() :
$id= Cv::select('cv.user_id','cv.pub')
->where('cv.pub','==',$this->request->pub)
->count();
This will return the number of records, 0 if none, 1 if one is found. Obviously this will only work if 1 record is found, if 3 are found this solution wont work however I from what you have said it seems like that is all you will return.
Anything more than 0 means that a value exists.

Return column value in Laravel 5.2

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');

Cannot retrieve single column from database. Laravel

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;
}

Categories