Laravel 10 Eloquent Where Not Equal To Condition Example
Hello Artisan, today I'll show you how to use laravel where condition not equal to in our Laravel application. "I'd like to show you how to use Laravel Eloquent to query records where the 'id' is not equal to a specific value." In Laravel's Eloquent, you can use the where method to specify conditions for your database queries, including situations where a column should not equal a particular value. You can achieve this by using either the != or <> operator. Here's an example that demonstrates both operators:
"Get all users where the status is anything other than '0'."
- Install Laravel App
- User Table
- Laravel Where Not Equal To using "!=" Operator
- Output
- Laravel Where Not Equal To using "<>" Operator
- Output
Creating the Laravel app is not necessary for this step, but if you haven't done it yet, you can proceed by executing the following command
composer create-project laravel/laravel-collection
Let's see the both example one by one:
You can see the simple code of UserController File.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$users = User::select("id", "name", "email", "status")
->where('status', '!=', '0')
->get();
dd($users);
}
}
Array
(
[0] => Array
(
[id] => 1
[name] => Admin User
[email] => [email protected]
[status] => 1
)
[1] => Array
(
[id] => 2
[name] => Staff User
[email] => [email protected]
[status] => 1
)
You can see the simple code of UserController File.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$users = User::select("id", "name", "email", "status")
->where('status', '<>', '0')
->get();
dd($users);
}
}
Array
(
[0] => Array
(
[id] => 1
[name] => Admin User
[email] => [email protected]
[status] => 1
)
[1] => Array
(
[id] => 2
[name] => Staff User
[email] => [email protected]
[status] => 1
)
That's it for today. I hope it'll be helpful in upcoming project. You can also download this source code from GitHub. Thanks for reading. ๐