0

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
    )

)

1
  • Why not just use SQL to select domain? / if not where('DOMAIN', 'odomain.com'), where('DOMAIN', 'like', '%doman.com%') is also an option Commented Aug 29, 2020 at 9:53

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.