joenpc npcsolution
joenpc npcsolution

Reputation: 767

How to use search value contain in array field using eloquent in Laravel

I'm working on laravel array serialize. Below is serialize in controller.

public function CreateSave(CreateTestTopicRequest $request){
    ...code..
    $testtopic->class_room_id = $request->classroom;
    $testtopic->roomno = serialize($request->roomno);
    ...code..
}

Then, roomno will be saved to database like.

a:2:{i:0;s:1:"1";i:1;s:1:"2";}

I would like to get result. For example class_room_id = 1 and roomno only contain in roomno array. I may use command to get all as below.

$testtopics = TestTopic::where('class_room_id',1)->get();

But, I do not know to get record only class_room_id = 1 and roomno contain in array. Any advice or guidance on this would be greatly appreciated, Thanks

Upvotes: 0

Views: 1132

Answers (2)

Morteza Negahi
Morteza Negahi

Reputation: 3493

You can use like search in json fields

TestTopic::where('class_room_id',1)->where('roomno', 'like', '%"id": 1%')->first()

Upvotes: 2

MaartenDev
MaartenDev

Reputation: 5802

When checking for an array of values the whereIn method can be used:

$roomno = 'a:2:{i:0;s:1:"1";i:1;s:1:"2";}';

$testtopics = TestTopic::where('class_room_id',1)
                    ->whereIn('roomno', unserialize($roomno))
                    ->get();

Multiple where statements can be combined by passing an array:

$roomno = 'a:2:{i:0;s:1:"1";i:1;s:1:"2";}';

$users = TestTopic::where([
    ['class_room_id', '=', '1'],
    ['roomno', '=', $roomno],
])->get();

Upvotes: 0

Related Questions