How to make mysql stick to a boolean pattern of querying in laravel

Viewed 15
public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('phone_no')->unique();
            $table->enum('role', ['admin', 'subadmin', 'user'])->index();
            $table->boolean('is_active')->default(false)->index();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->json('meta')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
    } 

return User::query()
        ->when($request->is_active, fn($query) => $query->where('is_active', $request->is_active))
        ->when($request->role, fn($query) => $query->where('role', $request->role))
        ->orderBy('created_at', 'desc')
        ->get();

if i pass is_active as false as a request, it filters by false, but if i filter by true it still shows false filter but if i pass the is_active request as 1, it then filter by true...What can i do to make it either i filter by true/false or 0/1..Thanks

1 Answers

You can cast the value as bool:

$query->where('is_active', (bool)$request->is_active)
Related