Created
November 10, 2016 12:17
-
-
Save adumskis/6d72e4816e09ec8dbe9ae57ce9d6aec1 to your computer and use it in GitHub Desktop.
Return object with row no in database
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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