Skip to content

Instantly share code, notes, and snippets.

@adumskis
Created November 10, 2016 12:17
Show Gist options
  • Save adumskis/6d72e4816e09ec8dbe9ae57ce9d6aec1 to your computer and use it in GitHub Desktop.
Save adumskis/6d72e4816e09ec8dbe9ae57ce9d6aec1 to your computer and use it in GitHub Desktop.
Return object with row no in database
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
class RowNoScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function apply(Builder $builder, Model $model)
{
if(is_null($builder->getQuery()->columns)){
$builder->addSelect('*');
}
DB::statement(DB::raw('set @row=0'));
$select = DB::raw('@row:=@row+1 as row_no');
$builder->addSelect($select);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment