Skip to content

Instantly share code, notes, and snippets.

@mathieutu
Created November 21, 2017 15:19
Show Gist options
  • Save mathieutu/bf5562fbff4b15a0b533a5e0756693fc to your computer and use it in GitHub Desktop.
Save mathieutu/bf5562fbff4b15a0b533a5e0756693fc to your computer and use it in GitHub Desktop.
Some functions to add to all Laravel models.
<?php
namespace App\Models;
abtract class Model extends \Illuminate\Database\Eloquent\Model
{
public function getLinkAttribute(): string
{
return route($this->getRouteName() . '.show', $this, false);
}
public function getRouteName(): string
{
return 'api.' . $this->getTable();
}
public static function factory()
{
return factory(static::class, ...func_get_args());
}
public static function fCreate($attributes = []): self
{
return static::factory()->create($attributes);
}
public function export($var_name = null, $_ = null): Collection
{
if (!$var_name) {
return collect($this->toArray());
}
$keys = is_array($var_name) ? $var_name : func_get_args();
return collect($keys)->mapWithKeys(function ($attribute) {
return [$attribute => $this->$attribute];
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment