Created
April 4, 2014 06:25
-
-
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?
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
| 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