Posts Learn Components Snippets Categories Tags Tools About
/

Search Eloquent Model by Slug in Laravel

Learn how to search your eloquent model by using the slug column instead of the ID field.

Created on Jul 04, 2021

1531 views

To search the eloquent model with "slug" or any other "non-ids" column in Laravel, you will have to make use of the "where" clause or set the particular column to be the primary key.

Using Where Clause
Since the "find" method can only accept the "id" by default, the only way is to use the "where" clause.
$posts = Post::where('slug', 'my-first-post')->first();

Use Slug Column as Identifier
By changing the primary key as the table identifier now the model itself will be queryable by the identifier column that you have defined. Under the hood, Laravel will make use of the "getQualifiedKeyName" to find the model.
<?php

namespace App\Models;

class Post extends Model
{
  protected $primaryKey = 'slug';

  // your other codes here
}

Now you can query your model using "find" and just pass in the "slug" as follows.
$post = Post::find('my-first-post');

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for Search Eloquent Model by Slug in Laravel

)