How to select row with the highest values in Laravel - laravel-4

I am trying to select 3 rows that have the 3 highest values in Laravel. How can I do this?
$data = DB::table('election')->select('election_id')->take(3)->max('votes');
This is not working

I was able to solve this issue by using the following code;
$data = DB::table('election')
->select('election_id', DB::raw("(select max('votes') from election)"))
->take(3)->get();

Related

Laravel Paginate with OrderBy

When querying a product code table I have the following
$results = Stock::orderBy('stk_physical', 'desc')->paginate(10);
This works fine on the initial load of 10 records but when a subsequent call is made for page 2 I get the following error
Incorrect syntax near 'offset'. (SQL: select * from [stock_records] order by [stk_physical] desc offset 10 rows fetch next 10 rows only)
I'm using Laravel 8.0 with SQL
You should append query string to the pagination like this
$results = Stock::orderBy('stk_physical', 'desc')->paginate(10);
$results->appends(["order_by" => "stk_physical"]);
This will append the &order_by=stk_physical to each link in the view and you can also use withQueryString() to take in consideration query string in future pagination like this
$results = Stock::orderBy('stk_physical', 'desc')->paginate(10)->withQueryString();

how to get latest record from the database having same id in laravel?

I am trying to to get latest record having the same id. For example
I have table
ID | Created_at
1 |2016-04-26
1 |2016-04-20
1 |2016-04-18
2 |2016-04-27
2 |2016-04-19
I want to get result like this
ID | Created_at
1 |2016-04-26
2 |2016-04-27
How do I do this in Laravel? I was only able to order the record by descending order. Don't know how to pick the latest record of each ID. Thank you.
Try using Collections service from laravel , and use last() method. Example:
$data = ModelName::all();
$last_data_object = collect($data)->last();
//try to see the object using var_dump()
var_dump($last_data_object);
I get it from https://laravel.com/docs/5.2/collections#method-last
You can try with whereRaw to getting last records in groupBy laravel
$data = Table::whereRaw('Created_at IN (select MAX(Created_at) FROM table GROUP BY ID)')->get();
Try it this way, it will give you the max grouped ID which will be the latest:
SELECT MAX(ID), Created_at
FROM table
GROUP BY ID, Created_at
Thank you everyone for help. I was able to solve this by
DB::raw("SELECT ID,created_at FROM <table name> a WHERE created_at=(SELECT max(created_at) FROM <table name> b WHERE a.ID=b.ID)
DB::raw('SELECT * FROM `test` WHERE 1 GROUP BY `ID` ORDER BY `Created_at` ASC');
Try this
Include the directive Db
$id = DB::table('your_table')->orderBy('id', 'desc')->value('id');
If you have user_id.
$id = DB::table('your_table')->where('user_id', $user_id)->orderBy('id', 'desc')->value('id');

How do I return last n records in the order of entry

From Laravel 4 and Eloquent ORM - How to select the last 5 rows of a table, but my question is a little different.
How do I return last N records ordered in the way they were created (ASC).
So for example the following records are inserted in order:
first
second
third
fourth
fifth
I want a query to return last 2 records
fourth
fifth
Laravel Offset
DB::table('users')->skip(<NUMBER Calulation>)->take(5)->get();
You can calculate N by getting the count of the current query and skipping $query->count() - 5 to get the last 5 records or whatever you wanted.
Ex
$query = User::all();
$count = ($query->count()) - 5;
$query = $query->skip($count)->get();
In pure SQL this is done by using a subquery. Something like this:
SELECT * FROM (
SELECT * FROM foo
ORDER BY created_at DES
LIMIT 2
) as sub
ORDER BY created_at ASC
So the limiting happens in the subquery and then in the main query the order by is reversed. Laravel doesn't really have native support for subqueries. However you can still do it:
$sub = DB::table('foo')->latest()->take(2);
$result = DB::table(DB::raw('(' . $sub->toSql() . ') as sub'))
->oldest()
->get();
And if you use Eloquent:
$sub = Foo::latest()->take(2);
$result = Foo::from(DB::raw('(' . $sub->toSql() . ') as sub'))
->oldest()
->get();
Note the latest and oldest just add an orderBy('created_at) with desc and asc respectively.

Select rows having 2 columns equal value in laravel Query builder

I want to write a query which selects rows where 2 attributes from 1 entity have equal value.
This would be an example of doing this in raw SQL:
Select * from users u where u.username = u.lastname
Does laravel have any methods that take 2 column names as parameters and return the matching results?
What you need is a DB::raw expression:
DB::table('users')
->where('username', '=', DB::raw('lastname'))
->get();
The only thing DB::raw actually does is to tell the query interpreter not to treat 'lastname' like any other string value but just interpolate it in the SQL as it is.
http://laravel.com/docs/queries#raw-expressions
In Laravel 5, there's now whereColumn for this, for cleaner code:
Users::whereColumn('username', 'lastname')->get();

Adding auto increment column in table in codeigniter

I am new to codeigniter. In my project I am getting some data from database and then showing them using codeigniter table->generate method. But I want to add an autoincrement column (like 1,2,3..) to show the row number in an additional column at the left of the table. Also, beside the number there will be checkbox to mark the row. Can anybody give me idea how can I do it in codeigniter?
You could add a count to your SQL query so that it is returned along with your results:
SET #n=0; SELECT #n := #n+1, * FROM example_table
Alternatively you could add the count to each result in PHP:
$count = 1;
foreach($results as $key => &$result){
array_push($result, $count);
$count++;
}
echo $this->table->generate($results);

Resources