Câu hỏi phỏng vấn Laravel
Câu hỏi

What are query scopes?

Câu trả lời

Query scopes in Laravel are a powerful feature of the Eloquent ORM that allow developers to encapsulate common query logic within model methods. These scopes can be reused throughout the application, making the code more readable and maintainable.

Types of Query Scopes

  1. Local Scopes:

    • Defined within an Eloquent model class.
    • Prefixed with the word scope by convention.
    • Used to add constraints to queries for a given model.
    • Example:
      php Copy
      class Post extends Model {
          public function scopeActive($query) {
              return $query->where('active', 1);
          }
      }
    • Usage:
      php Copy
      $activePosts = Post::active()->get();
  2. Dynamic Scopes:

    • Similar to local scopes but accept parameters to make the scope more flexible.
    • Example:
      php Copy
      class Post extends Model {
          public function scopeStatus($query, $status) {
              return $query->where('status', $status);
          }
      }
    • Usage:
      php Copy
      $publishedPosts = Post::status('published')->get();
  3. Global Scopes:

    • Applied to all queries for a given model.
    • Useful for adding constraints that should always be applied, such as soft deletes.
    • Example:
      php Copy
      class Post extends Model {
          protected static function boot() {
              parent::boot();
              static::addGlobalScope('active', function (Builder $builder) {
                  $builder->where('active', 1);
              });
          }
      }

Benefits of Using Query Scopes

  • Reusability: Scopes allow you to define common query constraints once and reuse them throughout your application.
  • Readability: Encapsulating query logic within scopes makes your code more readable and easier to ...
middle

middle

Gợi ý câu hỏi phỏng vấn

middle

How to Rollback one specific migration in Laravel?

middle

How do you generate migrations?

junior

What are artisan commands?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào