WhereJsonContains in Laravel

Hòa Nguyễn Coder

Published in Web Developer · Đã đăng vào tháng 5 9, 2024 1:12 AM

WhereJsonContains in Laravel. Ví dụ chúng ta có cột "note"  trong database, là kiểu json, dạng mảng. Có nghĩa là dữ liệu là mảng, chuyển sang json lưu vào database.

khi đó chúng ta có thể dùng whereJsonContains check các cặp key/value của nó


use App\Models\User;

Route::get('/', function () {
    /*
     //column note type (json) in database
     "note" => "[{"name": "PHP"}, {"name": "Laravel"}, {"name": "Next.js"}, {"name": "Vue.js"}, {"name": "React"}]"
    */

    /*
    //you can $request->note, after then json to array
    $notes = $request->note
    $notes = json_decode($note, true);
    */
    $notes = ["Laravel","Next.js"];

    $users = App\Models\User::query();
        if(count($notes)>0){
            foreach($notes as $position){
                $users->orWhereJsonContains('note', ['name' => $position]);
            }
        }

    //or
    $users2 = User::when($notes , function($query) use ($notes) {
            $query->where(function ($query) use ($notes) {
                foreach($notes as $position) {
                    $query->orWhereJsonContains('note', ['name' => $position]);
                }
            });
        });

    //Dump it
   dd($users->get()->toArray(),$users2->get()->toArray());
    //return view('welcome');
});

 

Nếu bạn thấy đem lại kiến thức bổ ích, hãy Click xem quảng cáo trên trang website của mình nhé! 🚀