How to find a record using a name in eloquent Laravel?

By default, we usually look for any record in the db table by id number. But I could not find how to search for any entry in the name column.

This is my code for finding a record and rendering 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 to make the URL display not as an identifier, but to display the message name, for example

some.com/category/name (instead of some.com/category/id)

+5
source share
1 answer

In your controller, you will always search for $id, as your Eloquent request uses:

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

int string (: any), $id .

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

}

, .

, Eloquent.

, .

class Author extends Eloquent {

}

, Author Authors - .

+20

All Articles