LaravelNovice:)'s avatar

Trying to update slug field for the whole table

I have a table "projects' with a filed 'slug' and 'project_name' . There are 80k entries.

I am trying to update the 'slug' field with a slug of the project_name.

My code is

 public function CreateSlug(){

        Projects::query()->update(['slug' => (Str::of('Review of '.( 'project_name' ))->slug('-'))]);

    }

The updation is happening but the file slug is populated without the content of the 'project_name' field. Its taking 'project_name' as a string. How can I use the field 'project_name' in this code ?

0 likes
8 replies
SilenceBringer's avatar

@kumarnaresh you use it entirely wrong. when you do mass update you can't use Str to do it. you need to do it entirely on mysql side

    public function CreateSlug()
    {
        Projects::query()->update([
            'slug' => \DB::raw('replace(lower(concat("Review of ", `project_name`)), " ", "-")')
        ]);
    }
1 like
LaravelNovice:)'s avatar

Thanks. Your code has updated the table field 'slug' appropriately. But the problem remains. When I try to use the slug in the url it ends up in 404 error .

Following is my code to display the url :

               <a href="{{ url('/Projectdetails/'.$item->id.'/'.$item->slug ) }}">
Tray2's avatar

And why do it in php since it's a one time thing. Just use sql.

1 like
LaravelNovice:)'s avatar

I tried it first in sql. But there are few issues. The url. of the slug does not work. But if I enter the slug manually for a row , it works. Raised this in another thread but could not get any proper solution. Thats why trying to do it like this. BTW I am a novice in laravel 8 :).

Tray2's avatar

You should be able to run

UPDATE projects
SET slug = replace(lower(concat("Review of ", `project_name`)), " ", "-");

But before you do make sure you have a backup of the table.

A tips is to use a select to see that you get the correct values before running the update.

SELECT replace(lower(concat("Review of ", `project_name`)), " ", "-") 
FROM projects;
1 like
Snapey's avatar

why would you want a slug with a space in it?

1 like
LaravelNovice:)'s avatar

The problem is solved. There was some issue with my route :). Thanks everybody for this timely help.

Please or to participate in this conversation.