Skip to content

Instantly share code, notes, and snippets.

@kamaroly
Last active June 23, 2020 06:47
Show Gist options
  • Save kamaroly/a5ed6d559f824e739871b8d4a80cd419 to your computer and use it in GitHub Desktop.
Save kamaroly/a5ed6d559f824e739871b8d4a80cd419 to your computer and use it in GitHub Desktop.
This trait adds path to your eloquent model ( $article->edit_path, $article->show_path, $article->update_path,$article->destroy_path).
<?php
use Exception;
trait EloquentRoutePaths {
/**
* Actions that are allowed to be performed on this
* Model
* @var array
*/
protected $actions = ['show','edit','update','destroy'];
/**
* Route name of this model, default is table name
* @var string
*/
protected $baseRouteName;
/**
* Get path for contribution
* @return string
*/
protected function path($action = 'edit')
{
if (! in_array($action,$this->actions)) {
throw new Exception("Invalid Route Action in Model passed", 1);
}
// If user exciplicitly defined the route property
// use it instead of default table name
if (empty($this->baseRouteName)) {
$this->baseRouteName = $this->getTable();
}
return route($this->baseRouteName.'.'.$action,$this);
}
/**
* Get edit path for this models
* @return string
*/
public function getEditPathAttribute()
{
return $this->path('edit');
}
/**
* Get show path for the route
* @return string
*/
public function getShowPathAttribute()
{
return $this->path('show');
}
/**
* Update Path for this model
* @return string
*/
public function getUpdatePathAttribute()
{
return $this->path('update');
}
/**
* Destroy path for this model
* @return string
*/
public function getDestroyPathAttribute()
{
return $this->path('destory');
}
}
@kamaroly
Copy link
Author

This trait adds http paths to your eloquent model, the goal is to have clean codes. It's inspired by a video I saw on.

   $Article->edit_path 
   $Article->show_path 
   $Article->update_path 
   $Article->destroy_path 

Usage

<?php
namespace App;

use Illuminate\Database\Eloquent\Model
use App\EloquentRoutePaths;

class Article extends Model
{
   use EloquentRoutePaths;
}

And in your html call the route like this.

    <a href="{{ $article->show_path }}" >Show</a>
    <a href="{{ $article->edit_path }}" >Edit</a>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment