Laravel Query Builder Where Exists Example (ok)

https://www.itsolutionstuff.com/post/laravel-5-query-builder-where-exists-exampleexample.html

Laravel Query Builder Where Exists Example

By Hardik Savani March 7, 2016 Category : PHP Laravel MySqlPauseUnmuteLoaded: 2.17%FullscreenVDO.AI

you use sql where exists clause in laravel. whereExists through you can use sql where exists clause in your laravel project. It is very easy to use and you can easily undestand. You can give SELECT statment in where condition. you can see bellow example and you can learn how to use whereExists in your app.

SQL Query

SELECT *FROM `items`WHERE EXISTS    (SELECT `items_city`.`id`     FROM `items_city`     WHERE items_city.item_id = items.id)

Using Laravel Query Builder

DB::table('items')    ->whereExists(function ($query) {        $query->select("items_city.id")              ->from('items_city')              ->whereRaw('items_city.item_id = items.id');    })    ->get();

Create Migrate

C:\xampp\htdocs\wpclidemo\routes\web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', [HomeController::class, 'index'])->name('home');
Route::get('/test', [HomeController::class, 'test'])->name('test');

C:\xampp\htdocs\wpclidemo\app\Http\Controllers\HomeController.php

Hoặc

C:\xampp\htdocs\wpclidemo\database\migrations\2022_08_10_085942_create_users_city_table.php

C:\xampp\htdocs\wpclidemo\database\factories\UsercityFactory.php

C:\xampp\htdocs\wpclidemo\app\Models\Usercity.php

C:\xampp\htdocs\wpclidemo\resources\views\tests.blade.php

Last updated

Was this helpful?