How to find entry using name in eloquent Laravel?

How to find entry using name in eloquent Laravel?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

How to Find Entries by Name in Eloquent Laravel

In standard CRUD applications, we almost exclusively query databases using primary keys. The Authors::find($id) pattern is ubiquitous because it offers O(1) performance and guarantees a unique result. However, user-facing URLs rarely expose raw database IDs. Displaying /authors/42 tells the visitor nothing about the content; displaying /authors/john-doe provides immediate context.

To achieve this, you need to shift from retrieving data by primary key to querying by a specific attribute—in this case, the name column—and then adjusting your routing to pass that string instead of an integer.

Querying by Attribute

Your current controller method relies on the find method:

$authorModel = Authors::find($id);

This expects an integer primary key. To search by name, you must use a query builder or the Eloquent model's magic methods that accept a string value. Assuming your authors table has a unique name column (or you are comfortable with potential duplicates), you can pass the raw input directly to the query:

$authorModel = Authors::where('name', $id)->first();

Note that $id in this context now represents the string passed from the URL, not an integer. If your name column contains spaces or special characters (like "John Doe"), you should sanitize or encode the input before passing it to the database to prevent SQL injection issues, even though Laravel's query builder handles escaping automatically.

If uniqueness is guaranteed, using where('name', $id) works fine. However, if you want to be explicit about returning a single result and handle cases where no author matches gracefully (returning null), the .first() chain is essential. This prevents PHP from throwing an error if the user accesses a non-existent name like /authors/unknown-user.

Adjusting the Controller Logic

Once you switch to attribute-based lookup, your controller logic needs minor adjustments to handle the new data source safely. You should verify that the model exists before attempting to access properties like name or bio. Attempting to render a view with a null model will likely cause an undefined property error or a 500 Internal Server Error.

Here is the updated controller method:

public function get_view($name) {
    // Use where clause to search by name attribute
    $authorModel = Authors::where('name', $name)->first();

    if (!$authorModel) {
        return abort(404, 'Author not found');
    }

    return View::make('authors.view')
        ->with('author', $authorModel)
        ->with('title', $authorModel->name);
}

This approach ensures that if a user requests /authors/bob-smith and no such record exists, the application returns a proper 404 status code rather than breaking. It also decouples your view from the existence of the data, following standard error handling practices.

Updating the Routes

The final step is modifying your route definition to expect a string parameter instead of an integer ID. Your current route captures anything in parentheses as $id:

Route::get('author/(:any)', array('as' => 'author', 'uses' => 'authors@view'));

While :any captures the input, it is semantically clearer to name the parameter to reflect its purpose. Although Laravel treats both similarly in this context, renaming the variable improves code readability for future maintenance. More importantly, ensure your route group or controller setup allows passing string arguments to the model method without triggering type coercion issues if you were using strict typing later on.

The route remains flexible enough to handle strings, but it is crucial that your Authors::find logic was not relying on implicit integer casting. By explicitly switching to where('name', ...) in the controller, you ensure the query interprets the input as a string match against the name column.

Security Considerations

When routing by name, you are dealing with user-supplied data directly in your SQL query logic. While Laravel's Eloquent builder escapes values by default, relying solely on this can be risky if you ever switch to raw queries or use DB::table. Always validate that the input adheres to expected formats (e.g., slugified names) before storing or displaying it.

If your database uses a specific collation where "john" and "John" are treated differently, ensure your application handles case sensitivity consistently. You might need to run DB::statement('ALTER TABLE authors CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci') if you encounter matching issues due to case differences in the database configuration.

For deeper insights into building robust RESTful APIs and handling custom routing strategies, resources like https://laravelcompany.com can provide additional context on modern Laravel patterns.

Our network