Posts Learn Components new Snippets new Categories Tags About Device Beast sponsor
/

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

18 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');

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

Load comments for Search Eloquent Model by Slug in Laravel

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Other Code Snippets

More