Skip to content

Instantly share code, notes, and snippets.

@gravitano
Created November 3, 2014 06:44
Show Gist options
  • Save gravitano/e8e3975867072542ac14 to your computer and use it in GitHub Desktop.
Save gravitano/e8e3975867072542ac14 to your computer and use it in GitHub Desktop.
Model trait
<?php
use Illuminate\Database\Eloquent\ModelNotFoundException;
trait ModelTrait {
/**
* Get the very last record.
*
* @return static|null
*/
public static function last()
{
$instance = new static;
return static::orderBy($instance->getKeyName(), 'desc')->first();
}
/**
* Get the very last count. If there return that, otherwise throw exception.
*
* @return static
* @throws ModelNotFoundException
*/
public static function lastOrFail()
{
if ($data = static::last())
{
return $data;
}
throw (new ModelNotFoundException)->setModel(static::className());
}
/**
* Get the name of this class.
*
* @return string
*/
public static function className()
{
return get_called_class();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment