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');
Leave a reply