laravel

how to use orWhere() method in Laravel


All the Eloquent relationships in Laravel are defined with methods. So, we can call those methods to get a reference of the database relationship without performing a query and get access to specific models. The orWhere() method is one of them. In this tutorial, you are going to learn how to use the orWhere() method in Laravel with examples-

Let’s assume we have a database table named customers. It is a simple table that contains some fields like id, name, email, phone, and address.

orWhere() method in Laravel

We simply want to retrieve user data from this table. Normally we can just do that through a customer’s id. But think of a case, where only id isn’t going to provide the correct information. We might need another unique field just like id, to get all the data. What can we do? To solve this problem we can use the orWhere() method.

The orWhere() method takes two arguments like orWhere(coulumn_name, value). At first, let’s use the method with the model.

Using model:

public function view(){

    $customers = Customer::select("name")
                          ->where('id', 2)
                          ->orWhere('phone', '22222')
                          ->get();
    return view('view_customer', compact('customers'));        
}

In this example, we have called the Customer model and wanted to know the name of the customer whose id is 2 and phone number is 22222 means If either one of the conditions is TRUE, then it’ll return the customer’s name. Then we simply passed the data with the compact() function.

HTML view:

<div class="container">
    <h1>Customer Name</h1><hr>
    @foreach ($customers as $data)
      <h3> {{$data->name}} </h3>
    @endforeach
</div>

We have received the retrieved data and performed a foreach loop to view the data-

OUTPUT:

orWhere() method in Laravel

Now we can also use the DB instead of the model. Suppose, we want to know all the information of a customer through his id and email address. The example is given below-

Using DB:

//use Illuminate\Support\Facades\DB;
public function view(){

    $customers = DB::table('customers')
                ->where('id', 1)
                ->orWhere('email', 'abir@gmail.com')
                ->get();

    return view('view_customer', compact('customers'));        
}

HTML view:

<div class="container">
  <h1>Customer details</h1><hr>
  @foreach ($customers as $data)
      <h4>Name: {{$data->name}} </h4>
      <h4>Phone: {{$data->phone}} </h4>
      <h4>Address: {{$data->address}} </h4>
  @endforeach
</div>

OUTPUT:

orWhere() method in Laravel

In this tutorial, you learned how to use the orWhere() method in Laravel. You can use it to solve more complex problems of your database. This is the very basic structure to use. I hope this tutorial is going to help you.


Share on social media

//