Rakhi
Rakhi

Reputation: 374

laravel - unable to get array of array format using any type of select query

please help me!!

Purpose - check Domain exist or not in given array, without using loop and all in laravel...

I want array format while run select Query. So, I can directly use the array functions. I have tried many ways but still not getting resolved..

My code as below :

$validDomains = DB::table('VALID_DOMAINS')->select('DOMAIN')->distinct()->get()->toArray();
 $Domain = 'testify.com';
if (!in_array($Domain, $validDomains)) {
                    echo 'Not in Array' . $Domain;
                } else {
                    echo 'In array :' . $Domain;
                }

But i'm getting result in $validDomains as below and that's why not performing operation without using any loop : Array ( [0] => stdClass Object ( [DOMAIN] => 0xx0.net )

[1] => stdClass Object
    (
        [DOMAIN] => 126.com
    )

[2] => stdClass Object
    (
        [DOMAIN] => 163.com
    )

[3] => stdClass Object
    (
        [DOMAIN] => 186design.co.uk
    )

[4] => stdClass Object
    (
        [DOMAIN] => 1stglobal.com
    )

)

Upvotes: 0

Views: 42

Answers (2)

mmabdelgawad
mmabdelgawad

Reputation: 2545

Just an explanation not a solution

toArray() you are using will convert the whole collection to array so you will get an array of objects however, to convert inner objects to array you need to map each object to array explicitly like so

DB::table('VALID_DOMAINS')->select('DOMAIN')->distinct()->get()->map(function ($object) {
    return (array)$object;
})->toArray();

Upvotes: 0

aleksejjj
aleksejjj

Reputation: 1835

Your way with pluck:

$validDomains = DB::table('VALID_DOMAINS')->select('DOMAIN')->distinct()->get()->pluck('DOMAIN')->toArray();

Right way:

$Domain = 'testify.com';
$validDomain = DB::table('VALID_DOMAINS')->select('DOMAIN')->where('DOMAIN', $Domain)->first();

if (!$validDomain)) {
    echo 'Not in Array' . $Domain;
} else {
    echo 'In array :' . $Domain;
}

Upvotes: 1

Related Questions