skip to Main Content

I am sure there is a similar question, but I am unsure what to search to find my answer (If you know what I am looking for, please just comment with the link or whatever you do). I need a way to pull all the countries allowed on a particular page (Just the name column in DB) and put it in an array. example:(United States, Canada, New Zealand, etc..) but in the database I have it set up when the pages are created to insert in the DB an array of the id #’s (id column in countries table) works perfectly fine inserts as (1,22,30, etc) 0 is not a countries table row, but I use 0 as the country ID for All Countries. I am just unsure where to start or how to "foreach" this. Here is a little bit of what I am trying to achieve in my Laravel controller:

public function view(Page $page, Request $request)
    {
        // $page->countries = array of country id's (1,12,14,etc)
        // How do i retrieve the country names
        $ip = $request->ip();
        $geo_info = Location::get($ip);
        $geo_country = $geo_info->country;
        $countries = Country = ??
            
            // How do I add the country names to an array (United States, Mexico, etc)
            // instead of the country id's while keeping the id's so its smaller data in the column for the page countries
        if(in_array($geo_country, $countries)) {
            return view();
        } else {
            return 'Country not allowed.';
        }
    }

How exactly would I format to pull the countries by the IDs and then attach only the country’s names column together in an array with ", "?

Sorry if this post is confusing, I am honestly confused myself.

2

Answers


  1. Could probably do something like this. Just create a empty array, loop then set the persisting data to that array. Hopefully this gives you an idea.

    $countries = array();
    foreach($geo_country as $countries) {
     $countries[] = $geo_country;
    }
    
    Login or Signup to reply.
  2. Assuming you have a Country model and corresponding table with country ID and country name, I think you are looking for a simple WHERE IN query, eg:

    // $page->countries = string list of country ids "1,2,3 ..."
    // Let's convert that to an array and use is in our query
    $allowed_countries = explode(',', $page->countries);
    $countries = Country::whereIn('id', $allowed_countries)->get();
    

    That should give you a Collection of your allowed countries. Now to check if $geo_country is in that collection (assuming the country name is in a field called name), you can use the contains() Collection method:

    if ($countries->pluck('name')->contains($geo_country)) {
        return view();
    } else {
        return 'Country not allowed.';
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search