Home / Snippets / Search Eloquent Model by Slug in Laravel
Search Eloquent Model by Slug in Laravel cover

Search Eloquent Model by Slug in Laravel

1.6K

3 years ago

0 comments

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');
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this