Skip to content

Instantly share code, notes, and snippets.

@afiqiqmal
Last active April 22, 2019 04:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afiqiqmal/23d42eb74e6048fb77c0e404e286ca3c to your computer and use it in GitHub Desktop.
Save afiqiqmal/23d42eb74e6048fb77c0e404e286ca3c to your computer and use it in GitHub Desktop.
Leverage Eloquent To Prepare Your URLs LARAVEL
<?php
/**
* Created by PhpStorm.
* User: hafiq
* Date: 21/04/2019
* Time: 7:17 PM
*/
namespace App\Http\Traits;
use App\Helpers\RouteUrlPresenter;
trait ModelRouteUrlGenerator
{
public static function bootModelRouteUrlGenerator()
{
static::retrieved(function ($model) {
$model->append('route');
});
}
protected function getDefaultRouteName()
{
return $this->getTable();
}
public function getRouteAttribute()
{
return RouteUrlPresenter::init($this, $this->prefixRouteName ?? $this->getDefaultRouteName());
}
}
<?php
/**
* Created by PhpStorm.
* User: hafiq
* Date: 21/04/2019
* Time: 8:05 PM
*/
namespace App\Helpers;
use Illuminate\Database\Eloquent\Model;
use InvalidArgumentException;
class RouteUrlPresenter
{
protected $model;
protected $routeName;
public function __construct(Model $model, $routeName = null)
{
$this->model = $model;
$this->routeName = $routeName ?? $model->getTable();
}
public function __call($name, $arguments)
{
return call_user_func_array(function() use ($name, $arguments) {
$argumentFlag = false;
if (count($arguments) > 0) {
$arguments = collect($arguments)->flatten()->values()->toArray();
$argumentFlag = $arguments[0] == -1;
}
array_unshift($arguments, $this->model->id);
if ($name == "index") {
try {
return route("$this->routeName.$name");
} catch (InvalidArgumentException $exception) {
return route("$this->routeName");
}
}
if ($argumentFlag) {
return route("$this->routeName.$name");
} else {
return route("$this->routeName.$name", $arguments);
}
}, $arguments);
}
public static function init(Model $model = null, $routeName = null)
{
return new self($model, $routeName);
}
}
<?php
$user->route->index(); // https://example.com/user
$user->route->update(); // https://example.com/user/1000/update
$user->route->update([200,300,400]); // https://example.com/user/1000/update/200/300/400 depending on route setup
$user->route->anyMethodRouteNameYouHave(YOU CAN YOU EXTRA ATTRIBUTE IF YOUR ROUTE HAVE MORE THAN 1 ATTRIBUTE EXCEPT ID);
$user->route->routeMethodName(-1); // -1 means no arguments needed in route
<?php
namespace App\Models;
use Afiqiqmal\LaraHashSlug\UseHashSlug;
use App\Http\Traits\ModelRouteUrlGenerator;
class Announcement extends Model
{
use ModelRouteUrlGenerator;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment