How to find entry using name in eloquent Laravel?

laravel, mysql, orm, php

Solution

In your controller you are always going to search by `$id` as your Eloquent query uses:

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

As your named route can be supplied with an int or string (:any) run a type check in the controller on `$id` and run a different query based on the result.

public function get_view($id)
{
   if (is_numeric($id))
   {
       $authorModel = Authors::find($id);
   }
   else
   {
       $column = 'name'; // This is the name of the column you wish to search

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

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

}

I hope that helps you.

As a side note, your Eloquent model.

There is no need for you to supply a table name if you use correct naming conventions.

class Author extends Eloquent {

}

Note the singular `Author` will map to a table called `Authors` automatically without any intervention from you.

Problem

By default we generally search any entry on db table by id number. But I could not find how to search any entry by the name column. This is my code for finding entry and rendering it to view Controller : Authors ``` class Authors_Controller extends Base_Controller { public $restful = true; public function get_view($id){ $authorModel = Authors::find($id); return View::make('authors.view') ->with('author', $authorModel) ->with('title', $authorModel->name); } } ``` Model : Authors ``` <?php class Authors extends Eloquent { public static $table = 'authors'; } ``` Route : ``` Route::controller(Controller::detect()); Route::get('author/(:any)', array('as'=>'author', 'uses'=>'authors@view')); ``` View : ``` @layout('main.index') @section('content') <h1>{{$author->name}}</h1> <p> {{$author->bio}} </p> <small> {{$author->created_at}} | {{HTML::link(URL::$base.'/authors/', 'Go back')}} </small> @endsection ``` How do i make the url as not to display id but to display the name of the post like some.com/category/name (instead of some.com/category/id)

Original source