Skip to content

Instantly share code, notes, and snippets.

@yfktn
Created April 4, 2014 06:25
Show Gist options
  • Select an option

  • Save yfktn/9969210 to your computer and use it in GitHub Desktop.

Select an option

Save yfktn/9969210 to your computer and use it in GitHub Desktop.
The trait use when we need function like Model::findOrFail(), but it used for slug. Or even the other field?
namespace app\lib\ModelSlug;
/**
* Imagine we have Category and Post, and we want to search for Post that are in Category, using a slug
* of Category.
*
* In controller ...
*
* $posts = Category::findSlugOrFail($theSlugFromRoute, $the_slug_field)->posts()->get();
*
* If failed, it will throw the same exception as findOrFail did.
*/
trait ModelSlug {
public static function findSlugOrFail($slug, $slugField='slug') {
if ( ! is_null($model = static::where($slugField, '=', $slug)->first())) return $model;
throw with(new ModelNotFoundException)->setModel(get_called_class());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment