<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: ysfjr1</title>
    <description>The latest articles on DEV Community by ysfjr1 (@ysfjr1).</description>
    <link>https://dev.to/ysfjr1</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F584916%2F64f850aa-7769-4e96-9755-15be12ca9808.png</url>
      <title>DEV Community: ysfjr1</title>
      <link>https://dev.to/ysfjr1</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ysfjr1"/>
    <language>en</language>
    <item>
      <title>Generate Slug Keyword from Title: Laravel + AJAX</title>
      <dc:creator>ysfjr1</dc:creator>
      <pubDate>Wed, 10 Mar 2021 13:02:32 +0000</pubDate>
      <link>https://dev.to/ysfjr1/generate-slug-keyword-from-title-laravel-ajax-2a8d</link>
      <guid>https://dev.to/ysfjr1/generate-slug-keyword-from-title-laravel-ajax-2a8d</guid>
      <description>&lt;p&gt;If you work with project or blog where records require so-called slug (posts, pages etc.), it’s convenient to generate slug immediately after title has been typed in. This article will show you how to do it in Laravel, with AJAX and with a help of one Laravel package.&lt;/p&gt;

&lt;p&gt;First, what we’re doing here. This is the example:&lt;/p&gt;

&lt;p&gt;We have a form to add a page, and our goal is to have Slug field auto-generated, as we finish typing in the Title.&lt;/p&gt;

&lt;p&gt;Not only that, slug should be unique for every post, even if title is the same.&lt;/p&gt;

&lt;h1&gt;
  
  
  Step 1. Blade Create Form
&lt;/h1&gt;

&lt;p&gt;I will show you, how resources/views/admin/pages/create.blade.php looks like. To be exact, the part responsible for those two fields – title and slug:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div class="form-group"&amp;gt;
    &amp;lt;label for="title"&amp;gt;Title*&amp;lt;/label&amp;gt;
    &amp;lt;input type="text" id="title" name="title" class="form-control"&amp;gt;
&amp;lt;/div&amp;gt;
&amp;lt;div class="form-group"&amp;gt;
    &amp;lt;label for="slug"&amp;gt;Slug*&amp;lt;/label&amp;gt;
    &amp;lt;input type="text" id="slug" name="slug" class="form-control"&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, the code is simple, nothing to comment here. Now, let’s add some JavaScript, that is fired when title value is changed.&lt;/p&gt;

&lt;h1&gt;
  
  
  Step 2. AJAX Call On Title Change
&lt;/h1&gt;

&lt;p&gt;In the “main” Blade layout file, I have a special @yield(‘scripts’) code that allows to add any JavaScript to any other Blade template. So, that’s exactly what we will do – add this code to the bottom of our pages/create.blade.php:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@section('scripts')
&amp;lt;script&amp;gt;
  $('#title').change(function(e) {
    $.get('{{ route('pages.check_slug') }}', 
      { 'title': $(this).val() }, 
      function( data ) {
        $('#slug').val(data.slug);
      }
    );
  });
&amp;lt;/script&amp;gt;
@endsection
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, we need to create the logic behind pages.check_slug route.&lt;/p&gt;

&lt;h1&gt;
  
  
  Step 3. Route/Controller to Return Slug
&lt;/h1&gt;

&lt;p&gt;First, in routes/web.php we add this line:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Route::get('pages/check_slug', 'PagesController@check_slug')
  -&amp;gt;name('pages.check_slug');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we create app/Http/Controllers/PagesController method check_slug(). We’ll start from a simple version using Laravel’s str_slug() helper.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function check_slug(Request $request)
{
    $slug = str_slug($request-&amp;gt;title);
    return response()-&amp;gt;json(['slug' =&amp;gt; $slug]);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Simple, right? We make a slug and return it. That could be the end of our tutorial, but we forgot one important rule – slugs should be unique. How to check it?&lt;/p&gt;

&lt;h1&gt;
  
  
  Step 4. Making Slug Unique
&lt;/h1&gt;

&lt;p&gt;Not only that, we need to not only check uniqueness, but also automatically add -1, -2, -3 and other numbers to the end of the slug, to generate a new unique one.&lt;/p&gt;

&lt;p&gt;For that, I’ve decided to not reinvent the wheel and to use an existing package eloquent-sluggable. It’s not the only slug-related package on the market, but it has a very useful (in our case) feature of generating slug without saving it to the database.&lt;/p&gt;

&lt;p&gt;We install the package with this command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;composer require cviebrock/eloquent-sluggable
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we need to prepare our Model app/Page.php to make it “sluggable”:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use Cviebrock\EloquentSluggable\Sluggable;

class Page extends Model
{
    use Sluggable;

    /**
     * Return the sluggable configuration array for this model.
     *
     * @return array
     */
    public function sluggable()
    {
        return [
            'slug' =&amp;gt; [
                'source' =&amp;gt; 'title'
            ]
        ];
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We’ve created a method that defines to generate slug field from title field of pages database table.&lt;/p&gt;

&lt;p&gt;And now, final step, we can replace old “simple” method of generating slug in PagesController:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use Cviebrock\EloquentSluggable\Services\SlugService;

public function check_slug(Request $request)
{
    // Old version: without uniqueness
    $slug = str_slug($request-&amp;gt;title);

    // New version: to generate unique slugs
    $slug = SlugService::createSlug(Page::class, 'slug', $request-&amp;gt;title);

    return response()-&amp;gt;json(['slug' =&amp;gt; $slug]);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And, that’s it!&lt;/p&gt;

</description>
      <category>laravel</category>
    </item>
  </channel>
</rss>
