php - Creating and storing dynamic URLs in laravel 8 by merging the values of two different arrays

I have two arrays and have to create 100000+ URLs, how can I achieve that?

array1['Car Shop', 'Bike Shop', 'Cycle Shop'];
array2['New Delhi', 'Jaipur', 'Gurgaon'];

Now I want this output:

array3['Car Shop In New Delhi', 'Car Shop In Jaipur', 'Car Shop In Gurgaon', 'Bike Shop In New Delhi', 'Bike Shop In Jaipur', 'Bike Shop In Gurgaon', 'Cycle Shop In New Delhi', 'Cycle Shop In Jaipur', 'Cycle Shop In Gurgaon',];

How to do this in laravel? Please help!

Answer

Solution:

You can combine your arrays using standard PHP functions, alternatively you can use some of the syntax sugar Laravel provides.

$collectionA = collect(['Car Shop', 'Bike Shop', 'Cycle Shop']);
$collectionB = collect(['New Delhi', 'Jaipur', 'Gurgaon', 'Mumbai', 'Raipur']);

$merged = $collectionA->map(function ($itemA, $indexA) use ($collectionB) {
    return $collectionB->map(function ($itemB, $indexB) use ($itemA) {
        return Str::slug($itemA . ' in ' . $itemB, '-');
    });
});

dd($merged->flatten()->toArray());

Which results in:

enter image description here

As you said you want to use the array3 in URLs, I suspect you'll want them as slugs.

You can then have a route that takes a slug as a parameter which you can use to query your database on:

Route::get('/shops/{slug}', [ShopController::class, 'show']);

public function show($slug)
{
    $shops = Shop::where('slug', $slug)->get();

    // etc.
}

Source