A
A
alt222018-02-06 00:36:16
Laravel
alt22, 2018-02-06 00:36:16

How to get post id in Laravel BEFORE adding it?

I want to add an id to the slug, for uniqueness, since the slug is formed from the header, and may already occur. How best to implement? Laravel 5.5

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Antonio Solo, 2018-02-06
@alt22

i check the new slug for uniqueness before saving. if non-unique - add time().rand()

D
Dmitry, 2018-02-06
@Astatroth

Is there any way to check for uniqueness with a validator? It's easier than making crutches.

A
Arman, 2018-02-06
@Arik

i make a url()/getUrl() method which will return "{$this->slug}-{$this->id}". store sense in db full slug?

A
alt22, 2018-02-06
@alt22

In general, I found this solution:

function getUniqueSlug($model, $slug)
    {
        if ($count = $model::where('slug', 'like', "$slug%")->count()) {
            $slug = str_finish($slug, "-$count");
        }
        return $slug;
    }

Without an id, but that's not bad either) The slug will be unique.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question