This content originally appeared on CodeSource.io and was authored by Anik Kanti Sikder Mithu
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.
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:
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:
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.
This content originally appeared on CodeSource.io and was authored by Anik Kanti Sikder Mithu
Anik Kanti Sikder Mithu | Sciencx (2022-02-11T09:10:58+00:00) how to use orWhere() method in Laravel. Retrieved from https://www.scien.cx/2022/02/11/how-to-use-orwhere-method-in-laravel/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.