harunB10
harunB10

Reputation: 5207

Create slug out of existing table using foreign key

I have a two tables - Campaigns and Products which are connected via foreign key (product_id)

Campaigns

|id| |product_id| |slug|

Products

|id| |product_name|

How can I generate slugs into slug column out of Products table.

For example product with product_name = "Pro Evolution Soccer 2017" has an id = 1. How can I generate the slug Pro-evolution-soccer-2017-1 into Campaigns table? Probably I should use Laravel helper function str_slug($title, $separator);, but I don't know how...

Btw I have a more than 500 000 products which need to be generated as slugs...

Upvotes: 0

Views: 982

Answers (2)

Captain Insaneo
Captain Insaneo

Reputation: 470

You should probably save this in the Products table on create and update. If you do this one time, in a separate table, it's going to cause issues if/when the Products.product_name changes.

$product->slug = str_slug($product->product_name, '-');

To update the existing items, you could create a migration to add the slug field to Product, then select all products, iterate through them, and set the slug value as I did above.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use App\Models\Product;

class CreateFlightsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('Products', function (Blueprint $table) {
            $table->string('slug');
        });

        foreach (Product::all() as $product) {
            $product->slug = str_slug($product->product_name, '-');
            $product->save();
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('Products', function (Blueprint $table) {
            $table->dropColumn('slug');
        });
    }
}

Then just php artisan migrate from the commandline.

Upvotes: 2

Nikolas
Nikolas

Reputation: 645

You can create a command to do this job documentation

and run a loop to create and save all these slugs via command line.

Also this method could be used in the future or schedule it to run often and fill the new empty rows.

Upvotes: 0

Related Questions