Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App;
- use Vinkla\Hashids\HashidsManager;
- /**
- * Bind a model to a route based on the hash of
- * its id (or other specified key).
- *
- * @package App
- *
- * @mixin \Illuminate\Database\Eloquent\Model
- */
- trait HashidsRoutable
- {
- /**
- * Instantiate appropriate Hashids connection
- *
- * @return \Hashids\Hashids
- */
- protected function getHashidsInstance()
- {
- return app(HashidsManager::class)->connection($this->getHashidsConnection());
- }
- /**
- * Determine Hashids connection to use
- *
- * @return null|string
- */
- protected function getHashidsConnection()
- {
- return null;
- }
- /**
- * Encode a parameter
- *
- * @param string $parameter
- * @return string
- */
- protected function encodeParameter($parameter)
- {
- return $this->getHashidsInstance()->encode($parameter);
- }
- /**
- * Decode parameter
- *
- * @param string $parameter
- * @return array
- */
- protected function decodeParameter($parameter)
- {
- return $this->getHashidsInstance()->decode($parameter);
- }
- /**
- * Instruct implicit route binding to use
- * our custom hashed parameter.
- *
- * This is long and crazy to avoid parameters
- * collisions.
- *
- * @return string
- */
- public function getRouteKeyName()
- {
- return 'hashidsRoutableHashParam';
- }
- /**
- * Determine which attribute to encode
- *
- * @return string
- */
- public function getRouteHashKeyName()
- {
- return $this->getKeyName();
- }
- /**
- * Get beginning value
- *
- * @return string
- */
- public function getRouteHashKey()
- {
- return $this->getAttribute($this->getRouteHashKeyName());
- }
- /**
- * Encode real parameter to url value for bindings
- *
- * @return string
- */
- public function getHashidsRoutableHashParamAttribute()
- {
- return $this->encodeParameter($this->getRouteHashKey());
- }
- /**
- * Transform a checking by hashed key to real query
- *
- * @return \Illuminate\Database\Eloquent\Builder
- */
- public function where()
- {
- $params = func_get_args();
- if ($params[0] == $this->getRouteKeyName()) {
- return parent::where($this->getRouteHashKeyName(), $this->decodeParameter($params[1]));
- }
- return parent::where(...$params);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement