Last active
July 10, 2020 11:14
-
-
Save tanthammar/64bf6a7c0c8ae9707e213e69c7af52f4 to your computer and use it in GitHub Desktop.
Laravel Append Model Links
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\Traits; | |
trait HasLinks | |
{ | |
/** | |
* Build link without passing route model binding params | |
* | |
* Instead of href="{{ route('prefix.modelplural.action', ['modelsingular' => 'have to remember model key', 'param' => 'value']) }}" | |
* href="{{$model->actionRoute('action', ['param'=>'value'])}}" | |
* example: href="{{$model->actionRoute('subscribe', ['subscription'=>'plan_xxxx'])}}" | |
* | |
* @param string $action | |
* @param array $params | |
* @param string $route_name_prefix | |
* @return string | |
*/ | |
public function actionRoute(string $action, array $params = [], string $route_name_prefix = 'app'): string | |
{ | |
$merged = array_merge([$this->routeKey => $this->{$this->getRouteKeyName()}], $params); | |
return route("{$route_name_prefix}.{$this->routePath}.{$action}", $merged); | |
} | |
public function getRouteKeyAttribute(): string | |
{ | |
return strtolower(class_basename($this)); | |
} | |
public function getRoutePathAttribute(): string | |
{ | |
return \Str::plural($this->routeKey); | |
} | |
public function getLinksAttribute(): array | |
{ | |
return [ | |
'index' => $this->indexRoute, | |
'show' => $this->showRoute, | |
'create' => $this->createRoute, | |
'edit' => $this->editRoute, | |
'delete' => $this->deleteRoute, | |
]; | |
} | |
public function getIndexRouteAttribute(): string | |
{ | |
return route("app.{$this->routePath}.index"); | |
} | |
public function getShowRouteAttribute(): string | |
{ | |
return route("app.{$this->routePath}.show", [$this->routeKey => $this->{$this->getRouteKeyName()}]); | |
} | |
public function getCreateRouteAttribute(): string | |
{ | |
return route("app.{$this->routePath}.create"); | |
} | |
public function getEditRouteAttribute(): string | |
{ | |
return route("app.{$this->routePath}.edit", [$this->routeKey => $this->{$this->getRouteKeyName()}]); | |
} | |
public function getDeleteRouteAttribute(): string | |
{ | |
return route("app.{$this->routePath}.delete", [$this->routeKey => $this->{$this->getRouteKeyName()}]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment