Skip to content

[Feature] Implement route-model binding by default #1052

Open
@Mosaab-Emam

Description

@Mosaab-Emam

Assuming laravel_generator.php:

return = [
  ...
  'repository_pattern' => false,
  'resources' => false,
  ...
]

And assuming we are generating a model named Post, here's what gets generated in PostController.php:

  // code

  public function show($id): JsonResponse
  {
      /** @var Post $post */
      $post = Post::find($id);

      if (empty($post)) {
          return $this->sendError(
              __('messages.not_found', ['model' => __('models/post.singular')])
          );
      }

      return $this->sendResponse(
          $post->toArray(),
          __('messages.retrieved', ['model' => __('models/post.singular')])
      );
  }

  // code

This does not implement route model binding, which is a sane default in any project with policies. For example, this pattern is required if the developer wishes to implement policies via middleware or via controller helpers.

My suggestion is to generate code similar to this:

  // code

  public function show(Post $post): JsonResponse
  {
      if (empty($post)) {
          return $this->sendError(
              __('messages.not_found', ['model' => __('models/post.singular')])
          );
      }

      return $this->sendResponse(
          $post->toArray(),
          __('messages.retrieved', ['model' => __('models/post.singular')])
      );
  }

  // code

This returns identical results, while helping implement policies out of the box.

The caveat is that it's not a sane default when using the repository pattern, so this should only apply when that option is set to false.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions