By Hardik Savani March 7, 2016 Category : PHP Laravel MySqlPauseUnmuteLoaded: 2.17%Fullscreen
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)
<?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');
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersCityTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users_city', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('user_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users_city');
}
}
<?php
namespace Database\Factories;
use App\Models\Usercity;
use Illuminate\Database\Eloquent\Factories\Factory;
class UsercityFactory extends Factory
{
protected $model = Usercity::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'name' => $this->faker->text,
'user_id' => $this->faker->numberBetween(1, 20),
];
}
}
C:\xampp\htdocs\wpclidemo\app\Models\Usercity.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Usercity extends Model
{
use HasFactory;
protected $table = 'users_city';
}