tarurexod
tarurexod

Reputation: 13

Check if exist and create

I try generate and save uncial slug for title in DB.

                $feed->friendlyUrl()->make([
                'url' => str_slug($feed->name),
                'action' => "feeds/{$feed->id}",
                'complicated' => false,
                'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,
            ]);

How check if such field in url exist? And if exist save:

'url' => str_slug($feed->name,"-1"),

I think:

  if (FriendlyUrl::whereUrl(str_slug($feed->name))){
            $feed->friendlyUrl()->make([
                'url' => str_slug($feed->name),
                'action' => "feeds/{$feed->id}",
                'complicated' => false,
                'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,
            ]);} else {
                $feed->friendlyUrl()->make([
                    'url' => str_slug($feed->name),
                    'action' => "feeds/{$feed->id}-1",
                    'complicated' => false,
                    'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE, 
            };
            break;

But it not clean and what if such url - str_slug($feed->name,"-1") already exists?

Upvotes: 0

Views: 985

Answers (3)

tarurexod
tarurexod

Reputation: 13

Unique slug for title

public static function boot()
           {
               parent::boot();

           static::creating(function($model) {
               $model->slug = str_slug($model->ToBeSluggified);// change the ToBeSluggiefied

               $latestSlug =
                   static::whereRaw("slug = '$model->slug' or slug LIKE '$model->slug-%'")
                       ->latest('id')
                       ->value('slug');
               if ($latestSlug) {
                   $pieces = explode('-', $latestSlug);

                   $number = intval(end($pieces));

                   $model->slug .= '-' . ($number + 1);
               }
           });
       }

Upvotes: 1

Mathieu Ferre
Mathieu Ferre

Reputation: 4412

You can use this :

$friendlyUrl = friendlyUrl::firstOrNew(
    ['url' => str_slug($feed->name,"-1")], [
                'action' => "feeds/{$feed->id}",
                'complicated' => false,
                'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,]
);

$friendlyUrl->save();

Upvotes: 1

Sachin Vairagi
Sachin Vairagi

Reputation: 5334

Try this -

$FriendlyUrl = FriendlyUrl::firstOrNew(array('url' => str_slug($feed->name)));
$FriendlyUrl->action = "feeds/{$feed->id}";
$FriendlyUrl->complicated = false;
$FriendlyUrl->page_type_id = PageType::TYPE_INDIVIDUAL_FEED_PAGE;
$FriendlyUrl->save();

Reference - Insert a new record if not exist and update if exist, laravel eloquent

Upvotes: 0

Related Questions