├── .php_cs ├── .styleci.yml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── app └── Http │ └── Controllers │ └── UserController.php ├── composer.json ├── config └── config.php ├── laravel-bullet.png └── src ├── Bullet.php ├── BulletServiceProvider.php ├── Controllers ├── BaseController.php └── ResourceController.php ├── Exceptions └── ModelNotFoundException.php ├── Facades └── Bullet.php ├── Resources └── DataResource.php └── Traits ├── BulletMiddleware.php ├── BulletPolicies.php ├── BulletRoutes.php ├── CrudHelpers.php ├── CrudOperations.php ├── DestroyAction.php ├── EditAction.php ├── ForceDeleteAction.php ├── IndexAction.php ├── RestoreAction.php ├── Searchable.php ├── ShowAction.php ├── StoreAction.php └── UpdateAction.php /.php_cs: -------------------------------------------------------------------------------- 1 | setRules(array( 5 | '@PSR2' => true, 6 | 'array_indentation' => true, 7 | 'array_syntax' => array('syntax' => 'short'), 8 | 'combine_consecutive_unsets' => true, 9 | 'method_separation' => true, 10 | 'no_multiline_whitespace_before_semicolons' => true, 11 | 'single_quote' => true, 12 | 13 | 'binary_operator_spaces' => array( 14 | 'align_double_arrow' => true, 15 | 'align_equals' => true, 16 | ), 17 | // 'blank_line_after_opening_tag' => true, 18 | 'blank_line_before_return' => true, 19 | 'braces' => array( 20 | 'allow_single_line_closure' => true, 21 | ), 22 | // 'cast_spaces' => true, 23 | // 'class_definition' => array('singleLine' => true), 24 | 'concat_space' => array('spacing' => 'one'), 25 | 'declare_equal_normalize' => true, 26 | 'function_typehint_space' => true, 27 | 'hash_to_slash_comment' => true, 28 | 'include' => true, 29 | 'lowercase_cast' => true, 30 | // 'native_function_casing' => true, 31 | // 'new_with_braces' => true, 32 | // 'no_blank_lines_after_class_opening' => true, 33 | 'no_blank_lines_after_phpdoc' => true, 34 | // 'no_empty_comment' => true, 35 | // 'no_empty_phpdoc' => true, 36 | // 'no_empty_statement' => true, 37 | 'no_extra_consecutive_blank_lines' => array( 38 | 'curly_brace_block', 39 | 'extra', 40 | 'parenthesis_brace_block', 41 | 'square_brace_block', 42 | 'throw', 43 | 'use', 44 | ), 45 | 'no_useless_return' => true, 46 | 'no_superfluous_elseif' => true, 47 | 'no_useless_else' => true, 48 | 'ordered_imports' => true, 49 | 50 | // 'no_leading_import_slash' => true, 51 | // 'no_leading_namespace_whitespace' => true, 52 | // 'no_mixed_echo_print' => array('use' => 'echo'), 53 | 'no_multiline_whitespace_around_double_arrow' => true, 54 | // 'no_short_bool_cast' => true, 55 | // 'no_singleline_whitespace_before_semicolons' => true, 56 | 'no_spaces_around_offset' => true, 57 | 'no_trailing_comma_in_list_call' => true, 58 | 'no_trailing_comma_in_singleline_array' => true, 59 | // 'no_unneeded_control_parentheses' => true, 60 | 'no_unused_imports' => true, 61 | 'no_whitespace_before_comma_in_array' => true, 62 | 'no_whitespace_in_blank_line' => true, 63 | // 'normalize_index_brace' => true, 64 | 'object_operator_without_whitespace' => true, 65 | //'php_unit_fqcn_annotation' => true, 66 | 67 | 'phpdoc_align' => [ 68 | 'align' => 'vertical', 69 | 'tags' => ['param', 'property', 'return', 'throws', 'type', 'var', 'method'], 70 | ], 71 | 'phpdoc_indent' => true, 72 | 'phpdoc_order' => true, 73 | 'phpdoc_scalar' => true, 74 | 'phpdoc_separation' => true, 75 | 'phpdoc_no_alias_tag' => true, 76 | 'phpdoc_trim' => true, 77 | //'phpdoc_annotation_without_dot' => true, 78 | //'phpdoc_inline_tag' => true, 79 | //'phpdoc_no_access' => true, 80 | //'phpdoc_no_alias_tag' => true, 81 | //'phpdoc_no_empty_return' => true, 82 | //'phpdoc_no_package' => true, 83 | //'phpdoc_no_useless_inheritdoc' => true, 84 | //'phpdoc_return_self_reference' => true, 85 | //'phpdoc_scalar' => true, 86 | //'phpdoc_separation' => true, 87 | //'phpdoc_single_line_var_spacing' => true, 88 | //'phpdoc_summary' => true, 89 | //'phpdoc_to_comment' => true, 90 | //'phpdoc_trim' => true, 91 | //'phpdoc_types' => true, 92 | //'phpdoc_var_without_name' => true, 93 | 94 | // 'pre_increment' => true, 95 | // 'return_type_declaration' => true, 96 | // 'self_accessor' => true, 97 | // 'short_scalar_cast' => true, 98 | 'single_blank_line_before_namespace' => true, 99 | // 'single_class_element_per_statement' => true, 100 | // 'space_after_semicolon' => true, 101 | // 'standardize_not_equals' => true, 102 | 'ternary_operator_spaces' => true, 103 | 'trailing_comma_in_multiline_array' => true, 104 | 'trim_array_spaces' => true, 105 | 'unary_operator_spaces' => true, 106 | 'whitespace_after_comma_in_array' => true, 107 | )) 108 | //->setIndent("\t") 109 | ->setLineEnding("\n") 110 | ; -------------------------------------------------------------------------------- /.styleci.yml: -------------------------------------------------------------------------------- 1 | preset: laravel 2 | 3 | disabled: 4 | - single_class_element_per_statement 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to `laravel-bullet` will be documented in this file 4 | 5 | ## 1.0.0 - 201X-XX-XX 6 | 7 | - initial release 8 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Marco Túlio 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Laravel Bullet](https://raw.githubusercontent.com/marcoT89/laravel-bullet/master/laravel-bullet.png) 2 | 3 | # Laravel Bullet 4 | 5 | [![Latest Version on Packagist](https://img.shields.io/packagist/v/marcot89/laravel-bullet.svg?style=flat-square)](https://packagist.org/packages/marcot89/laravel-bullet) 6 | [![Total Downloads](https://img.shields.io/packagist/dt/marcot89/laravel-bullet.svg?style=flat-square)](https://packagist.org/packages/marcot89/laravel-bullet) 7 | 8 | 9 | 10 | ⚡️ Lightning fast CRUDs and routes registrations for Laravel Applications 11 | 12 | This package gives you the power to make API Cruds to eloquent resources very fast, and you can use its dynamic routes registration based on conventions. If you don't like scaffolds, and don't like the repetitive crud operations and route registration for resources, this is the right package for you and your applications. 13 | 14 | ## Table of Contents 15 | 16 | - [Installation](#Installation) 17 | - [Basic Usage](#Basic-Usage) 18 | - [Dynamic Routes](#Dynamic-Routes) 19 | - [Middleware Configuration](#Middleware-Configuration) 20 | - [Policy Classes](#Policy-Classes) 21 | - [Validations and Requests](#Validations-and-Requests) 22 | - [Action Hooks](#Action-Hooks) 23 | - [API Resources (Presentation)](#API-Resources-Presentation) 24 | - [Actions in Details](#Actions-in-Details) 25 | - [Pagination, Filters and Other Magics](#Pagination-Filters-and-Other-Magics) 26 | - [Custom Query Builder for Actions](#Custom-Query-Builder-for-Actions) 27 | - [Custom Actions](#Custom-Actions) 28 | - [Advanced Routes](#Advanced-Routes) 29 | - [Custom HTTP Methods](#Custom-HTTP-Methods) 30 | - [Route params and dependency injection](#Route-params-and-dependency-injection) 31 | - [Performance and Other Tips](#Performance-and-Other-Tips) 32 | - [Only use public methods for actions](#Only-use-public-methods-for-actions) 33 | - [Use `route:cache` command to increase performance](#Use-routecache-command-to-increase-performance) 34 | - [HTML and JSON responses](#HTML-and-JSON-responses) 35 | - [Changelog](#Changelog) 36 | - [Contributing](#Contributing) 37 | - [Security](#Security) 38 | - [Credits](#Credits) 39 | - [License](#License) 40 | - [Laravel Package Boilerplate](#Laravel-Package-Boilerplate) 41 | 42 | ## Installation 43 | 44 | You can install the package via composer: 45 | 46 | ```bash 47 | composer require marcot89/laravel-bullet 48 | ``` 49 | 50 | > **Recommended:** This package recommends the usage of [Laravel Query Builder](https://github.com/spatie/laravel-query-builder) from [Spatie](https://github.com/spatie) team for index actions. 51 | 52 | ## Basic Usage 53 | 54 | Simply extend the `ResourceController` in your controller class: 55 | 56 | ```php 57 | **Important:** The methods `forceDelete` and `restore` is only displayed if the resource method use the laravel's trait `SoftDeletes`. 80 | 81 | > **Convention:** The resource model is infered by the convention. If you have a controller called `PostController` it will infer the model `Post`. The convention for the controller name is something like: `[Model]Controller` and it **will not** try to resolve from plural to singular. So if you define a controller `PostsController` it will try to resolve the model `Posts` instead of `Post`. Keep this in mind when creating your controllers. 82 | 83 | That's it! This is sufficient to add crud actions to your controller. But **what about define the routes dynamically?** Thats what we're going to see next. 84 | 85 | ## Dynamic Routes 86 | 87 | Now that you created a `UserController` it is time to register the routes for the resource controller right? 88 | But what if those routes could be registered automatically? Ok! Lets do it! 89 | 90 | Use `Bullet::namespace` in any group of routes you want. Example: 91 | 92 | ```php 93 | // routes/web.php 94 | Route::middleware('auth', function () { 95 | Bullet::namespace('Resources'); // the default namespace is App\Http\Controllers 96 | }); 97 | ``` 98 | 99 | And that's it! Now **all** controllers created under `Resources` namespace will have their public methods registered automatically. This are the following routes: 100 | 101 | | HTTP | URL | Route Name | Controller@action | Middleware | 102 | | --------- | ----------------- | ------------- | ----------------------------------------------------- | ---------- | 103 | | GET\|HEAD | users | users.index | App\Http\Controllers\Resources\UserController@index | web,auth | 104 | | POST | users | users.store | App\Http\Controllers\Resources\UserController@store | web,auth | 105 | | PUT | users/{user} | users.update | App\Http\Controllers\Resources\UserController@update | web,auth | 106 | | DELETE | users/{user} | users.destroy | App\Http\Controllers\Resources\UserController@destroy | web,auth | 107 | | GET\|HEAD | users/{user} | users.show | App\Http\Controllers\Resources\UserController@show | web,auth | 108 | | GET\|HEAD | users/{user}/edit | users.edit | App\Http\Controllers\Resources\UserController@edit | web,auth | 109 | 110 | If you want to hide some specific route or action you can use the `$only` or `$except` protected properties of the controller to do so: 111 | 112 | ```php 113 | class UserController extends ResourceController 114 | { 115 | protected $only = ['index', 'show']; 116 | // or 117 | protected $except = ['destroy']; 118 | } 119 | ``` 120 | This will generate only the expected routes as defined. 121 | 122 | >**NOTE:** keep in mind that the `$only` property has precedence over `$except` property and they cannot be used together. 123 | 124 | >**IMPORTANT:** The `$only` property will hide all other actions including the dynamic ones. 125 | 126 | ## Middleware Configuration 127 | 128 | Because we use dynamic routes, the middleware configuration is set on a controller property. Here are some examples: 129 | 130 | ```php 131 | // You can set only one middleware for all actions 132 | protected $middleware = 'auth'; 133 | // or many middlewares 134 | protected $middleware = ['auth', 'verified']; 135 | // or customized for different actions 136 | protected $middleware = [ 137 | 'auth', 138 | 'auth:api' => ['except' => 'index'], 139 | 'verified' => ['only' => ['store', 'update', 'destroy']] 140 | ]; 141 | ``` 142 | 143 | ## Policy Classes 144 | 145 | The policy classes are used automatically if you follow the convention. If the model of your controller is `User`, for example, laravel-bullet will try to register a `UserPolicy` policy class automatically. But it will skip the authorization if the policy class doesn't exist. 146 | 147 | If you want a customized policy class to your controller you can set the property `$policy` in your controller. Like this: 148 | 149 | ```php 150 | class UserController extends ResourceController 151 | { 152 | protected $policy = \App\Policies\CustomUserPolicy::class; 153 | } 154 | ``` 155 | If you don't want a policy class to be registered even if it exists to a controller, you can just set the `$policy` property to `false`. 156 | 157 | >**TIP:** Policy classes are registered automatically, you **don't need** to register it in the `AuthServiceProvider`. 158 | 159 | ## Validations and Requests 160 | 161 | The validations are encouraged to be used in the request classes. The requests are automatically injected through conventions. If you have a model `User` in the controller and the current action is `store`, laravel-bullet will try to inject a request class in this following convention order: 162 | 163 | ```php 164 | App\Http\Requests\Users\StoreRequest::class 165 | App\Http\Requests\UserStoreRequest::class 166 | ``` 167 | 168 | If none of those classes above exists, it will inject the default laravel `Illuminate\Http\Request` class. 169 | 170 | And if you want to customize the request class to a specific action, you can define it in the `requests` protected property in controller: 171 | 172 | ```php 173 | use App\Http\Requests\MyCustomUserRequest; 174 | 175 | class UserController extends ResourceController 176 | { 177 | protected $requests = [ 178 | 'store' => MyCustomUserRequest::class, 179 | ]; 180 | } 181 | ``` 182 | 183 | Now the request `MyCustomUserRequest` class will be injected in the store action. 184 | 185 | **Old School Validations** 186 | 187 | If you don't like validations in request classes, or just prefer the laravel `validate` method, you can use in the action hooks: 188 | 189 | ```php 190 | class UserController extends ResourceController 191 | { 192 | protected function beforeStore($request, $attributes) 193 | { 194 | return $this->validate($request, [ 195 | 'name' => 'required', 196 | 'email' => 'required|email', 197 | 'password' => 'required|min:6|confirmed', 198 | ]); 199 | } 200 | } 201 | ``` 202 | 203 | You can find more about action hooks in the next topic. 204 | 205 | ## Action Hooks 206 | 207 | It is very common to perform some operations in case of success or fail of an action. For example emit events, log, dispatch jobs etc. All crud actions has a `before` and a `after` hook actions. 208 | 209 | They are very usefull, for example for encrypt passwords for users: 210 | 211 | ```php 212 | class UserController extends ResourceController 213 | { 214 | protected function beforeStore($request, $attributes): array 215 | { 216 | $attributes['password'] = bcrypt($attributes['password']); 217 | 218 | return $attributes; 219 | } 220 | } 221 | ``` 222 | 223 | Or to emit an event when a user is created: 224 | 225 | ```php 226 | use App\Events\UserCreated; 227 | 228 | class UserController extends ResourceController 229 | { 230 | protected function afterStore($request, $user) 231 | { 232 | event(new UserCreated($user)); 233 | } 234 | } 235 | ``` 236 | 237 | Here is a list of the declarative action hooks for each action: 238 | 239 | ```php 240 | // Hooks for index action 241 | protected function beforeIndex($request); 242 | protected function afterIndex($request, $builder); 243 | 244 | // Hooks for store action 245 | protected function beforeStore($request, $attributes): array; // should return the attributes for the model being stored. 246 | protected function afterStore($request, $model); 247 | 248 | // Hooks for update action 249 | protected function beforeUpdate($request, $attributes, $model): array; 250 | protected function afterUpdate($request, $model); 251 | 252 | // Hooks for destroy action 253 | protected function beforeDestroy($request, $model); 254 | protected function afterDestroy($request, $model); 255 | 256 | // Hooks for show action 257 | protected function beforeShow($request, $model); 258 | protected function afterShow($request, $model); 259 | 260 | // Hooks for edit action 261 | protected function beforeEdit($request, $model); 262 | protected function afterEdit($request, $model); 263 | 264 | // Hooks for forceDelete action 265 | protected function beforeForceDelete($request, $model); 266 | protected function afterForceDelete($request, $model); 267 | 268 | // Hooks for restore action 269 | protected function beforeRestore($request, $model); 270 | protected function afterRestore($request, $model); 271 | ``` 272 | 273 | ## API Resources (Presentation) 274 | 275 | To set your own API Resource you can use the protected `resource` property in the controller class. Example: 276 | 277 | ```php 278 | use App\Http\Resources\UserResource; 279 | 280 | class UserControlle extends ResourceController 281 | { 282 | protected $resource = UserResource::class; 283 | } 284 | ``` 285 | 286 | > **NOTE:** this resource will be used in all actions. 287 | 288 | ## Actions in Details 289 | 290 | #### Pagination, Filters and Other Magics 291 | If you use the recommended [Laravel Query Builder](https://github.com/spatie/laravel-query-builder) composer package you should be able to use all of it's features very easy. Before dive into the examples bellow read their documentation and be familiarized with their usage. 292 | 293 | All of these properties are available for the **index** and **show** actions: 294 | 295 | ```php 296 | protected $defaultSorts = null; 297 | protected $allowedFilters = null; 298 | protected $allowedIncludes = null; 299 | protected $allowedSorts = null; 300 | protected $allowedFields = null; 301 | protected $allowedAppends = null; 302 | protected $defaultPerPage = 15; 303 | protected $maxPerPage = 500; 304 | protected $searchable = true; 305 | ``` 306 | 307 | > **WARNING:** This set of properties only works with [Laravel Query Builder](https://github.com/spatie/laravel-query-builder) package. It **WILL NOT WORK** without it. 308 | 309 | See how it works: 310 | 311 | **$defaultSorts** 312 | ```php 313 | // Sort your records from latest to oldest by default 314 | protected $defaultSorts = '-created_at'; 315 | ``` 316 | 317 | **$allowedFilters** 318 | ```php 319 | protected $allowedFilters = ['name', 'email']; 320 | ``` 321 | Or you can use the `allowedFilters` method to a more complete case: 322 | ```php 323 | protected function allowedFilters() 324 | { 325 | return [ 326 | 'name', 327 | AllowedFilter::exact('id'), 328 | AllowedFilter::exact('email')->ignore(null), 329 | AllowedFilter::scope('with_trashed'), 330 | AllowedFilter::custom('permission', FilterUserPermission::class), 331 | ]; 332 | } 333 | ``` 334 | 335 | **$allowedIncludes** 336 | ```php 337 | protected $allowedIncludes = ['posts.comments']; 338 | ``` 339 | Or you can use the `allowedIncludes` method to a more complete case: 340 | ```php 341 | protected function allowedIncludes() 342 | { 343 | $includes = ['posts.comments']; 344 | 345 | if (user()->isAdmin()) { 346 | $includes[] = 'created_by'; 347 | $includes[] = 'logs'; 348 | } 349 | 350 | return $includes; 351 | } 352 | ``` 353 | 354 | **$allowedSorts** 355 | ```php 356 | protected $allowedSorts = ['id', 'name', 'created_at']; 357 | ``` 358 | Or you can use the `allowedSorts` method to a more complete case: 359 | ```php 360 | protected function allowedSorts() 361 | { 362 | return [ 363 | 'id', 364 | 'name', 365 | 'created_at', 366 | Sort::field('street', 'actual_column_street'), 367 | ]; 368 | } 369 | ``` 370 | 371 | **$allowedFields** 372 | ```php 373 | protected $allowedFields = ['id', 'name', 'email']; 374 | ``` 375 | Or you can use the `allowedFields` method to a more complete case: 376 | ```php 377 | protected function allowedFields() 378 | { 379 | return [ 380 | 'id', 381 | 'name', 382 | 'email', 383 | ]; 384 | } 385 | ``` 386 | 387 | **$allowedAppends** 388 | ```php 389 | protected $allowedAppends = ['is_admin', 'is_published']; 390 | ``` 391 | Or you can use the `allowedAppends` method to a more complete case: 392 | ```php 393 | protected function allowedAppends() 394 | { 395 | return ['is_admin', 'is_published']; 396 | } 397 | ``` 398 | 399 | **$defaultPerPage** 400 | ```php 401 | protected $defaultPerPage = 15; // defaults to 15 402 | ``` 403 | This can be passed by the `per_page` or `perPage` query params. 404 | 405 | **$maxPerPage** 406 | ```php 407 | protected $maxPerPage = 500; // defaults to 500 408 | ``` 409 | But the `per_page` or `perPage` params cannot pass this `$maxPerPage` limit. If you pass a `per_page=1000` the pagination will limit to 300 if you have defined it. This is a protection to your queries. Use it wisely. 410 | 411 | **$searchable** 412 | ```php 413 | protected $searchable = true; // defaults to true 414 | ``` 415 | By default all index actions accepts the `search` query param, and it will try to use a `scopeSearch` scope in the model if it's present. If it's not present it just ignores it. Set it to false if you have a search scope in your model but you don't want to make it available in your index action. 416 | 417 | #### Custom Query Builder for Actions 418 | There are many times that you have a big scope for your queries. For example if you are developing a multitenant application with `teams` some times you want to list the users of the current user's team. For that case you could customize the queries for the controller. For now, each of the actions has its own query method. 419 | 420 | For index action you should override the `getQuery` method, like this: 421 | 422 | ```php 423 | protected function getQuery() 424 | { 425 | return team()->users(); 426 | } 427 | ``` 428 | Here are the complete list of actions for the query builder to override when needed: 429 | 430 | ```php 431 | protected function getQuery($request); // for index action 432 | protected function getStoreQuery($request); 433 | protected function getUpdateQuery($request); 434 | protected function getDestroyQuery($request); 435 | protected function getShowQuery($request); 436 | protected function getEditQuery($request); 437 | protected function getForceDeleteQuery($request); 438 | protected function getRestoreQuery($request); 439 | ``` 440 | 441 | #### Custom Actions 442 | 443 | To completly customize a crud action you just need to declare it as it is expected. For limitation reasons all routes that need `$id` to find a model is given with `$id` param instead of the typed model object. Also it's not possible to inject request classes due to its declaration. For example, if you want to customize the update method that receives an `$id` you should do: 444 | 445 | ```php 446 | public function update($id) 447 | { 448 | $user = User::findOrFail($id); 449 | ... 450 | } 451 | ``` 452 | 453 | Now you can do whatever you want with the action method. 454 | ## Advanced Routes 455 | 456 | When using the bullet dynamic routes you don't have to write any route manually in any of the route files. With bullet routes any public method in the controller becomes an action with a registered route. Example: 457 | 458 | ```php 459 | class UserController extends ResourceController 460 | { 461 | public function reports() 462 | { 463 | ... 464 | } 465 | } 466 | ``` 467 | 468 | The **public** method will **automatically** register a route like this: 469 | 470 | ```php 471 | Route::get('users/reports', 'Resources\UserController@reports')->name('users.reports'); 472 | ``` 473 | 474 | #### Custom HTTP Methods 475 | 476 | If you want to customize the **http method** of the route just prefix it with the name of the http method. Like this: 477 | 478 | ```php 479 | public function postReports() 480 | { 481 | ... 482 | } 483 | ``` 484 | 485 | Now, the public method `postReports` will register a route with post http method: 486 | 487 | ```php 488 | Route::post('users/reports', 'Resources\UserController@postReports')->name('users.reports'); 489 | ``` 490 | > **HINT:** Note that the generated **route name** was `'users.reports'` instead of `'users.post-reports'`. 491 | 492 | #### Route params and dependency injection 493 | 494 | You can also pass arguments to the action and they will be converted to url params. 495 | 496 | ```php 497 | use App\Models\User; 498 | use App\Http\Requests\MyCustomRequest; 499 | 500 | class UserController extends ResourceController 501 | { 502 | public function postReports(MyCustomRequest $request, User $user, $report, $param1, $param2) // as many as you want. 503 | { 504 | ... 505 | } 506 | } 507 | ``` 508 | 509 | Now this public method will register a route like this: 510 | 511 | ```php 512 | Route::post('users/reports/{user}/{report}/{param1}/{param2}', 'Resources\UserController@postReports')->name('users.post-reports'); 513 | ``` 514 | 515 | > **NOTE:** Any typed param will be injected normally as expected. And request params will be injected but ignored in the route definition. 516 | 517 | #### Excluding Controller From Dynamic Routes 518 | 519 | Sometimes you have to define a very custom routes for one of your controllers. To exclude your controller from the dynamic routes you should use the `options` parameters on `namespace` method. Like this: 520 | 521 | ```php 522 | Bullet::namespace('Api/V1', ['except' => 'InternalController']); 523 | ``` 524 | Now the routes for this controller won't be generated dynamically. You have to register its routes **manually**. 525 | 526 | ## Performance and Other Tips 527 | 528 | #### Only use public methods for actions 529 | 530 | Since the public methods in the controller will register a route automatically, it's a good practice to use `protected` or `private` visibility for other helper methods to not generate **trash routes**. 531 | 532 | #### Use `route:cache` command to increase performance 533 | 534 | Since the laravel-bullet uses a lot of reflection and IO for every controller classes, using `route:cache` command for production environments will **increase significantly the performance** of your requests. 535 | 536 | #### HTML and JSON responses 537 | The actions `index` responds to json if it's an AJAX request, or will try to return a view under `resources/views/users/index.blade.php`. 538 | 539 | 544 | 545 | ## Changelog 546 | 547 | Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently. 548 | 549 | ## Contributing 550 | 551 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 552 | 553 | ### Security 554 | 555 | If you discover any security related issues, please email marcotulio.avila@gmail.com instead of using the issue tracker. 556 | 557 | ## Credits 558 | 559 | - [Marco Túlio](https://github.com/marcot89) 560 | - [All Contributors](../../contributors) 561 | 562 | ## License 563 | 564 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 565 | 566 | ## Laravel Package Boilerplate 567 | 568 | This package was generated using the [Laravel Package Boilerplate](https://laravelpackageboilerplate.com). 569 | -------------------------------------------------------------------------------- /app/Http/Controllers/UserController.php: -------------------------------------------------------------------------------- 1 | loadTranslationsFrom(__DIR__.'/../resources/lang', 'bullet'); 18 | // $this->loadViewsFrom(__DIR__.'/../resources/views', 'bullet'); 19 | // $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); 20 | // $this->loadRoutesFrom(__DIR__.'/routes.php'); 21 | 22 | if ($this->app->runningInConsole()) { 23 | $this->publishes([ 24 | __DIR__.'/../../config/config.php' => config_path('bullet.php'), 25 | ], 'config'); 26 | 27 | // Publishing the views. 28 | /*$this->publishes([ 29 | __DIR__.'/../resources/views' => resource_path('views/vendor/laravel-bullet'), 30 | ], 'views');*/ 31 | 32 | // Publishing assets. 33 | /*$this->publishes([ 34 | __DIR__.'/../resources/assets' => public_path('vendor/laravel-bullet'), 35 | ], 'assets');*/ 36 | 37 | // Publishing the translation files. 38 | /*$this->publishes([ 39 | __DIR__.'/../resources/lang' => resource_path('lang/vendor/laravel-bullet'), 40 | ], 'lang');*/ 41 | 42 | // Registering package commands. 43 | // $this->commands([]); 44 | } 45 | } 46 | 47 | /** 48 | * Register the application services. 49 | */ 50 | public function register() 51 | { 52 | // Automatically apply the package configuration 53 | // $this->mergeConfigFrom(__DIR__.'/../../config/config.php', 'bullet'); 54 | 55 | // Register the main class to use with the facade 56 | $this->app->singleton('laravel-bullet', function () { 57 | return new Bullet; 58 | }); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/Controllers/BaseController.php: -------------------------------------------------------------------------------- 1 | registerMiddleware(); 10 | 11 | if (method_exists($this, 'registerPolicy')) { 12 | $this->registerPolicy(); 13 | } 14 | } 15 | 16 | protected function registerMiddleware() 17 | { 18 | $middlewares = []; 19 | $this->middleware = is_string($this->middleware) ? [$this->middleware] : $this->middleware; 20 | foreach ($this->middleware as $middleware => $options) { 21 | if (!is_string($middleware)) { 22 | $middleware = $options; 23 | $options = []; 24 | } 25 | $middlewares[] = compact('middleware', 'options'); 26 | } 27 | $this->middleware = $middlewares; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Traits/BulletPolicies.php: -------------------------------------------------------------------------------- 1 | policy ?? null; 12 | 13 | if (class_exists($this->getModel()) && 14 | class_exists($this->getModelPolicy()) && 15 | $policy !== false) { 16 | Gate::policy($this->getModel(), $this->getModelPolicy()); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Traits/BulletRoutes.php: -------------------------------------------------------------------------------- 1 | namespace = $namespace ?? ''; 24 | $this->controllerInstances = []; 25 | 26 | if (isset($options['except'])) { 27 | collect($options['except'])->each(function ($controller) { 28 | $this->ignoreClasses[] = $this->getNamespaced($controller); 29 | }); 30 | } 31 | 32 | $controllers = $this->mapMethods($this->getControllers()); 33 | 34 | $this->makeRoutes($controllers); 35 | } 36 | 37 | private function getControllers(): Collection 38 | { 39 | $dirs = new \IteratorIterator(new \DirectoryIterator(app_path('Http/Controllers/' . $this->namespace))); 40 | $files = collect(); 41 | foreach ($dirs as $file) { 42 | if ($file->isDir() || $file->getBasename() === 'Controller.php') { 43 | continue; 44 | } 45 | $files->push(str_replace('.php', '', $file->getBasename())); 46 | } 47 | 48 | return $files->filter(function ($controller) { 49 | return class_exists($this->getNamespaced($controller)); 50 | }); 51 | } 52 | 53 | private function getNamespaced($controller) 54 | { 55 | $namespace = str_replace('/', '\\', $this->namespace); 56 | 57 | return str_replace('\\\\', '\\', Str::studly('App\\Http\\Controllers\\' . $namespace . '\\' . $controller)); 58 | } 59 | 60 | private function getNamespacedForRoute($controller) 61 | { 62 | $namespaced = $this->getNamespaced($controller); 63 | 64 | return str_replace('App\\Http\\Controllers\\', '', $namespaced); 65 | } 66 | 67 | private function mapMethods(Collection $controllers): Collection 68 | { 69 | return $controllers->mapWithKeys(function ($controller) { 70 | $class = new \ReflectionClass($this->getNamespaced($controller)); 71 | $methods = collect($class->getMethods())->filter(function ($method) { 72 | return $method->isPublic() 73 | && !Str::startsWith($method->name, '__') 74 | && !collect($this->ignoreClasses)->contains($method->class); 75 | })->map->name->values()->toArray(); 76 | 77 | return [$controller => $methods]; 78 | }); 79 | } 80 | 81 | private function makeRoutes(Collection $controllers) 82 | { 83 | foreach ($controllers as $controllerName => $actions) { 84 | $controller = $this->getNamespacedForRoute($controllerName); 85 | foreach ($actions as $action) { 86 | $httpMethod = $this->inferHttpMethodFromActionName($action); 87 | $model = class_basename($this->getModelFromController($controllerName)); 88 | $url = $this->getRouteOf($controllerName, $model, $action); 89 | $route = $this->getRouteNameFrom($controllerName); 90 | $routeName = Str::kebab($this->sanitizeMethodName($action)); 91 | 92 | if (!$this->shouldDisplayRoute($controllerName, $action)) { 93 | continue; 94 | } 95 | 96 | Route::{$httpMethod}("$url", "$controller@$action")->name("$route.$routeName"); 97 | } 98 | } 99 | } 100 | 101 | private function shouldDisplayRoute($controller, $action) 102 | { 103 | $only = collect($this->getControllerPropValue($controller, 'only')); 104 | $except = collect($this->getControllerPropValue($controller, 'except')); 105 | $implementsSoftDelete = false; 106 | $softDeleteActions = collect(['forceDelete', 'restore']); 107 | 108 | if ($softDeleteActions->contains($action)) { 109 | $model = $this->getModelFromController($controller); 110 | $modelObj = new $model(); 111 | $implementsSoftDelete = method_exists($modelObj, 'initializeSoftDeletes'); 112 | 113 | return $implementsSoftDelete && $only->isEmpty() && $except->isEmpty() 114 | || ($implementsSoftDelete && $only->isNotEmpty() && $only->contains($action)) 115 | || ($implementsSoftDelete && $only->isEmpty() && !$except->contains($action)); 116 | } 117 | 118 | if ($only->isNotEmpty()) { 119 | return $only->contains($action); 120 | } 121 | 122 | if ($except->isNotEmpty()) { 123 | return !$except->contains($action); 124 | } 125 | 126 | return true; 127 | } 128 | 129 | private function getRouteOf(string $controller, string $model, string $action) 130 | { 131 | $defaultRoute = $this->getRouteNameFrom($controller); 132 | $modelSlug = Str::kebab($model); 133 | $modelInVariableFormat = Str::camel($modelSlug); 134 | $methodSlug = Str::kebab($this->sanitizeMethodName($action)); 135 | $urlParams = $this->getMethodParametersOf($controller, $action) 136 | ->map(function (\ReflectionParameter $param) { 137 | return '{' . $param->getName() . '}'; 138 | })->implode('/'); 139 | 140 | switch ($action) { 141 | case 'index': 142 | return $defaultRoute; 143 | case 'update': 144 | case 'show': 145 | case 'destroy': 146 | return "$defaultRoute/{" . $modelInVariableFormat . '}'; 147 | case 'forceDelete': 148 | return "$defaultRoute/{" . $modelInVariableFormat . '}/force-delete'; 149 | case 'restore': 150 | return "$defaultRoute/{" . $modelInVariableFormat . '}/restore'; 151 | case 'edit': 152 | return "$defaultRoute/{" . $modelInVariableFormat . '}/edit'; 153 | case 'store': 154 | return "$defaultRoute"; 155 | default: 156 | return "$defaultRoute/$methodSlug/$urlParams"; 157 | } 158 | } 159 | 160 | private function getRouteNameFrom(string $controller) 161 | { 162 | $names = explode('_', Str::snake($controller)); 163 | array_pop($names); 164 | 165 | return Str::plural(implode('-', $names)); 166 | } 167 | 168 | private function getMethodParametersOf(string $controller, string $method): Collection 169 | { 170 | $controller = $this->getNamespaced($controller); 171 | $ref = new \ReflectionClass($controller); 172 | 173 | return collect($ref->getMethod($method)->getParameters())->filter(function (\ReflectionParameter $param) { 174 | if (!$param->hasType() || $param->getClass() === null) { 175 | return $param; 176 | } 177 | 178 | return !$param->getClass()->isSubclassOf('Illuminate\\Http\\Request') 179 | && $param->getType()->getName() !== 'Illuminate\\Http\\Request'; 180 | })->values(); 181 | } 182 | 183 | private function sanitizeMethodName(string $method): string 184 | { 185 | $sanitized = $method; 186 | 187 | $this->httpMethods()->each(function ($httpMethod) use (&$sanitized) { 188 | if (Str::startsWith($sanitized, $httpMethod) && (strlen($sanitized) !== strlen($httpMethod))) { 189 | $sanitized = substr($sanitized, strlen($httpMethod)); 190 | } 191 | }); 192 | 193 | return $sanitized; 194 | } 195 | 196 | private function inferHttpMethodFromActionName(string $method) 197 | { 198 | $resourceMethods = collect([ 199 | 'index', 200 | 'store', 201 | 'update', 202 | 'show', 203 | 'create', 204 | 'edit', 205 | 'destroy', 206 | 'forceDelete', 207 | 'restore', 208 | ]); 209 | 210 | if ($resourceMethods->contains($method)) { 211 | return $this->getResourceHttpMethodFrom($method); 212 | } 213 | 214 | list($httpMethod) = explode('-', Str::kebab($method)); 215 | 216 | return $this->httpMethods()->contains($httpMethod) ? $httpMethod : 'get'; 217 | } 218 | 219 | private function httpMethods(): Collection 220 | { 221 | if ($this->httpMethods) { 222 | return $this->httpMethods; 223 | } 224 | 225 | return $this->httpMethods = collect(['get', 'post', 'put', 'patch', 'delete']); 226 | } 227 | 228 | private function getResourceHttpMethodFrom(string $method) 229 | { 230 | switch ($method) { 231 | case 'index': 232 | case 'show': 233 | case 'edit': 234 | case 'create': 235 | return 'get'; 236 | case 'store': 237 | return 'post'; 238 | case 'update': 239 | case 'restore': 240 | return 'put'; 241 | case 'destroy': 242 | case 'forceDelete': 243 | return 'delete'; 244 | } 245 | throw new \LogicException('There is no http method defined for the resource method "' . $method . '"'); 246 | } 247 | 248 | private function getModelFromController(string $controller) 249 | { 250 | $model = $this->getControllerPropValue($controller, 'model'); 251 | 252 | // Infer model name from controller 253 | list($controller) = explode('-', Str::kebab($controller)); 254 | 255 | return $model ?? 'App\\Models\\' . Str::studly($controller); 256 | } 257 | 258 | private function getControllerInstance($controller) 259 | { 260 | $controller = class_basename($controller); 261 | $controller = $this->getNamespaced($controller); 262 | 263 | return $this->controllerInstances[$controller] = $this->controllerInstances[$controller] 264 | ?? $this->createControllerInstance($controller); 265 | } 266 | 267 | private function createControllerInstance($controller) 268 | { 269 | $controller = class_basename($controller); 270 | $controllerClass = $this->getNamespaced($controller); 271 | 272 | $controllerObject = resolve($controllerClass); 273 | 274 | return is_string($controllerObject) ? new $controllerObject : $controllerObject; 275 | } 276 | 277 | private function getControllerPropValue($controller, $property) 278 | { 279 | $object = $this->getControllerInstance($controller); 280 | $reflection = new \ReflectionObject($object); 281 | 282 | if (!$reflection->hasProperty($property)) { 283 | return null; 284 | } 285 | 286 | $prop = $reflection->getProperty($property); 287 | $prop->setAccessible(true); 288 | 289 | return $prop->getValue($object); 290 | } 291 | } 292 | -------------------------------------------------------------------------------- /src/Traits/CrudHelpers.php: -------------------------------------------------------------------------------- 1 | model ?? Str::singular(str_replace('Controller', '', $controller)); 18 | 19 | if (class_exists($model)) { 20 | return $this->model = $model; 21 | } 22 | if (class_exists('App\\Models\\' . $model)) { 23 | return $this->model = 'App\\Models\\' . $model; 24 | } 25 | if (class_exists('App\\' . $model)) { 26 | return $this->model = 'App\\' . $model; 27 | } 28 | throw new ModelNotFoundException("Model $model not found for controller $controller"); 29 | } 30 | 31 | protected function getQuery() 32 | { 33 | return $this->getModel()::query(); 34 | } 35 | 36 | protected function getFilteredQuery($request) 37 | { 38 | $query = $this->getQuery(); 39 | 40 | if (class_exists('Spatie\QueryBuilder\QueryBuilder')) { 41 | $query = \Spatie\QueryBuilder\QueryBuilder::for($query) 42 | ->defaultSorts($this->defaultSorts()) 43 | ->allowedFilters($this->allowedFilters()) 44 | ->allowedFields($this->allowedFields()) 45 | ->allowedIncludes($this->allowedIncludes()) 46 | ->allowedSorts($this->allowedSorts()) 47 | ->allowedAppends($this->allowedAppends()); 48 | } 49 | 50 | return $query; 51 | } 52 | 53 | protected function modelHasMethod($method) 54 | { 55 | $model = $this->getModel(); 56 | $model = new $model(); 57 | 58 | return method_exists($model, $method); 59 | } 60 | 61 | protected function getModelUrl() 62 | { 63 | return Str::slug(Str::plural(class_basename($this->getModel()))); 64 | } 65 | 66 | protected function getPluralModelVariableName() 67 | { 68 | return Str::camel(Str::plural(class_basename($this->getModel()))); 69 | } 70 | 71 | protected function getSingularModelVariableName() 72 | { 73 | return Str::camel(Str::singular(class_basename($this->getModel()))); 74 | } 75 | 76 | protected function getModelResource() 77 | { 78 | if (isset($this->resource)) { 79 | return $this->resource ?: DataResource::class; 80 | } 81 | 82 | $resource = class_basename($this->getModel()) . 'Resource'; 83 | $resourceClass = 'App\\Http\\Resources\\' . $resource; 84 | 85 | if (class_exists($resourceClass)) { 86 | return $resourceClass; 87 | } 88 | 89 | return DataResource::class; 90 | } 91 | 92 | protected function getModelPolicy() 93 | { 94 | if (isset($this->policy)) { 95 | return $this->policy; 96 | } 97 | 98 | $model = class_basename($this->getModel()); 99 | 100 | return "App\\Policies\\{$model}Policy"; 101 | } 102 | 103 | protected function getModelColumns() 104 | { 105 | $modelClass = $this->getModel(); 106 | $model = new $modelClass(); 107 | 108 | return $this->modelColumns = $this->modelColumns ?? Schema::getColumnListing($model->getTable()); 109 | } 110 | 111 | protected function resolveRequestForAction($action) 112 | { 113 | $capitalizedAction = ucfirst($action); 114 | $model = class_basename($this->getModel()); 115 | $modelPlural = Str::plural($model); 116 | $requestsNamespace = 'App\\Http\\Requests'; 117 | 118 | if (isset($this->requests) && Arr::has($this->requests, $action)) { 119 | return resolve($this->requests[$action]); 120 | } 121 | 122 | if (class_exists("$requestsNamespace\\{$modelPlural}\\{$capitalizedAction}Request")) { 123 | return resolve("$requestsNamespace\\{$modelPlural}\\{$capitalizedAction}Request"); 124 | } 125 | 126 | if (class_exists("$requestsNamespace\\{$model}{$capitalizedAction}Request")) { 127 | return resolve("$requestsNamespace\\{$model}{$capitalizedAction}Request"); 128 | } 129 | 130 | return resolve(Request::class); 131 | } 132 | 133 | protected function authorizeAction($action, $modelObject = null) 134 | { 135 | $ability = method_exists($this, 'resourceAbilityMap') 136 | ? ($this->resourceAbilityMap()[$action] ?? $action) 137 | : $action; 138 | 139 | if (class_exists($this->getModelPolicy()) && method_exists($this, 'authorize')) { 140 | $this->authorize($ability, $modelObject ?? $this->getModel()); 141 | } 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /src/Traits/CrudOperations.php: -------------------------------------------------------------------------------- 1 | resolveRequestForAction('destroy'); 13 | $model = $this->getDestroyQuery($request)->findOrFail($id); 14 | $this->authorizeAction('destroy', $model); 15 | 16 | return DB::transaction(function () use ($request, $model) { 17 | $model = $this->beforeDestroy($request, $model) ?? $model; 18 | $model->delete(); 19 | $model = $this->afterDestroy($request, $model) ?? $model; 20 | 21 | return response()->json(null, Response::HTTP_NO_CONTENT); 22 | }); 23 | } 24 | 25 | protected function getDestroyQuery($request) 26 | { 27 | return $this->getModel()::query(); 28 | } 29 | 30 | protected function beforeDestroy($request, $model) 31 | { 32 | return $model; 33 | } 34 | 35 | protected function afterDestroy($request, $model) 36 | { 37 | return $model; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/Traits/EditAction.php: -------------------------------------------------------------------------------- 1 | resolveRequestForAction('edit'); 12 | $model = $this->getEditQuery($request)->findOrFail($id); 13 | $this->authorizeAction('edit', $model); 14 | 15 | return DB::transaction(function () use ($request, $model) { 16 | $model = $this->beforeEdit($request, $model) ?? $model; 17 | $model = $this->afterEdit($request, $model) ?? $model; 18 | 19 | return view($this->getModelUrl() . '.edit', [ 20 | $this->getSingularModelVariableName() => $model, 21 | ]); 22 | }); 23 | } 24 | 25 | protected function getEditQuery($request) 26 | { 27 | return $this->getFilteredQuery($request); 28 | } 29 | 30 | protected function beforeEdit($request, $model) 31 | { 32 | return $model; 33 | } 34 | 35 | protected function afterEdit($request, $model) 36 | { 37 | return $model; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/Traits/ForceDeleteAction.php: -------------------------------------------------------------------------------- 1 | resolveRequestForAction('forceDelete'); 13 | $model = $this->getForceDeleteQuery($request)->findOrFail($id); 14 | $this->authorizeAction('forceDelete', $model); 15 | 16 | return DB::transaction(function () use ($request, $model) { 17 | $model = $this->beforeForceDelete($request, $model) ?? $model; 18 | $model->forceDelete(); 19 | $model = $this->afterForceDelete($request, $model) ?? $model; 20 | 21 | return response()->json(null, Response::HTTP_NO_CONTENT); 22 | }); 23 | } 24 | 25 | protected function getForceDeleteQuery($request) 26 | { 27 | return $this->getModel()::withTrashed(); 28 | } 29 | 30 | protected function beforeForceDelete($request, $model) 31 | { 32 | return $model; 33 | } 34 | 35 | protected function afterForceDelete($request, $model) 36 | { 37 | return $model; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/Traits/IndexAction.php: -------------------------------------------------------------------------------- 1 | resolveRequestForAction('index'); 10 | $this->authorizeAction('index'); 11 | $this->beforeIndex($request); 12 | 13 | $perPage = $request->per_page ?? $request->perPage ?? $this->defaultPerPage; 14 | $perPage = $perPage <= 0 ? 1 : $perPage; 15 | $perPage = $perPage > $this->maxPerPage ? $this->maxPerPage : $perPage; 16 | 17 | $query = $this->getIndexQuery($request); 18 | $query = $this->afterIndex($request, $query); 19 | 20 | $collection = $query->paginate($perPage); 21 | 22 | if ($request->wantsJson()) { 23 | return $this->getModelResource()::collection($collection); 24 | } 25 | 26 | return view($this->getModelUrl() . '.index', [ 27 | $this->getPluralModelVariableName() => $this->getModelResource()::collection($collection) 28 | ->toResponse($request)->getData(true), 29 | ]); 30 | } 31 | 32 | protected function beforeIndex($request) 33 | { 34 | } 35 | 36 | protected function afterIndex($request, $builder) 37 | { 38 | return $builder; 39 | } 40 | 41 | protected function getIndexQuery($request) 42 | { 43 | $query = $this->getFilteredQuery($request); 44 | 45 | if ($this->searchable && $this->modelHasMethod('scopeSearch')) { 46 | $query->search($request->search); 47 | } 48 | 49 | return $query; 50 | } 51 | 52 | protected function defaultSorts() 53 | { 54 | return $this->defaultSorts ?? []; 55 | } 56 | 57 | protected function allowedFilters() 58 | { 59 | return $this->allowedFilters ?? []; 60 | } 61 | 62 | protected function allowedIncludes() 63 | { 64 | return $this->allowedIncludes ?? []; 65 | } 66 | 67 | protected function allowedSorts() 68 | { 69 | return $this->allowedSorts ?? $this->getModelColumns(); 70 | } 71 | 72 | protected function allowedFields() 73 | { 74 | return $this->allowedFields ?? $this->getModelColumns(); 75 | } 76 | 77 | protected function allowedAppends() 78 | { 79 | return $this->allowedAppends ?? []; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/Traits/RestoreAction.php: -------------------------------------------------------------------------------- 1 | resolveRequestForAction('restore'); 12 | $model = $this->getRestoreQuery($request)->findOrFail($id); 13 | $this->authorizeAction('restore', $model); 14 | 15 | return DB::transaction(function () use ($request, $model) { 16 | $model = $this->beforeRestore($request, $model) ?? $model; 17 | $model->restore(); 18 | $model = $this->afterRestore($request, $model) ?? $model; 19 | 20 | return $this->getModelResource()::make($model); 21 | }); 22 | } 23 | 24 | protected function getRestoreQuery($request) 25 | { 26 | return $this->getModel()::withTrashed(); 27 | } 28 | 29 | protected function beforeRestore($request, $model) 30 | { 31 | return $model; 32 | } 33 | 34 | protected function afterRestore($request, $model) 35 | { 36 | return $model; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Traits/Searchable.php: -------------------------------------------------------------------------------- 1 | searchableFields()); 16 | if ($fields->isEmpty()) { 17 | return $query; 18 | } 19 | 20 | $firstField = $fields->shift(); 21 | $driver = optional($this->getConnection())->getDriverName() ?? 'mysql'; 22 | $like = $driver === 'pgsql' ? 'ilike' : 'like'; 23 | 24 | $query->where($firstField, $like, '%' . strtolower($search) . '%'); 25 | 26 | foreach ($fields as $field) { 27 | $query->orWhere($field, $like, '%' . strtolower($search) . '%'); 28 | } 29 | 30 | return $query; 31 | } 32 | 33 | public function searchableFields() 34 | { 35 | return $this->searchableFields ?? []; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Traits/ShowAction.php: -------------------------------------------------------------------------------- 1 | resolveRequestForAction('show'); 12 | $model = $this->getShowQuery($request)->findOrFail($id); 13 | $this->authorizeAction('show', $model); 14 | 15 | return DB::transaction(function () use ($request, $model) { 16 | $model = $this->beforeShow($request, $model) ?? $model; 17 | $model = $this->afterShow($request, $model) ?? $model; 18 | 19 | return $this->getModelResource()::make($model); 20 | }); 21 | } 22 | 23 | protected function getShowQuery($request) 24 | { 25 | return $this->getFilteredQuery($request); 26 | } 27 | 28 | protected function beforeShow($request, $model) 29 | { 30 | return $model; 31 | } 32 | 33 | protected function afterShow($request, $model) 34 | { 35 | return $model; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Traits/StoreAction.php: -------------------------------------------------------------------------------- 1 | resolveRequestForAction('store'); 12 | $this->authorizeAction('store'); 13 | 14 | $attributes = method_exists($request, 'validated') 15 | ? ($request->validated()) 16 | : ($request->all()); 17 | 18 | return DB::transaction(function () use ($attributes, $request) { 19 | $attributes = $this->beforeStore($request, $attributes) ?? $attributes; 20 | $modelObject = $this->getStoreQuery($request)->create($attributes); 21 | 22 | $modelObject = $this->afterStore($request, $modelObject) ?? $modelObject; 23 | 24 | return $this->getModelResource()::make($modelObject); 25 | }); 26 | } 27 | 28 | protected function getStoreQuery($request) 29 | { 30 | return $this->getModel()::query(); 31 | } 32 | 33 | protected function beforeStore($request, $attributes): array 34 | { 35 | return $attributes; 36 | } 37 | 38 | protected function afterStore($request, $model) 39 | { 40 | return $model; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Traits/UpdateAction.php: -------------------------------------------------------------------------------- 1 | resolveRequestForAction('update'); 12 | $model = $this->getUpdateQuery($request)->findOrFail($id); 13 | $this->authorizeAction('update', $model); 14 | 15 | $attributes = method_exists($request, 'validated') 16 | ? ($request->validated()) 17 | : ($request->all()); 18 | 19 | return DB::transaction(function () use ($attributes, $request, $model) { 20 | $attributes = $this->beforeUpdate($request, $attributes, $model) ?? $attributes; 21 | $model->update($attributes); 22 | $model = $this->afterUpdate($request, $model) ?? $model; 23 | 24 | return $this->getModelResource()::make($model); 25 | }); 26 | } 27 | 28 | protected function getUpdateQuery($request) 29 | { 30 | return $this->getModel()::query(); 31 | } 32 | 33 | protected function beforeUpdate($request, $attributes, $model): array 34 | { 35 | return $attributes; 36 | } 37 | 38 | protected function afterUpdate($request, $model) 39 | { 40 | return $model; 41 | } 42 | } 43 | --------------------------------------------------------------------------------