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)
Searching Eloquent models Imagine you need to provide a search for users. Using Eloquent you can perform a search like this: User::query() ->where('name', 'LIKE', "%{$searchTerm}%") ->orWhere('email', 'LIKE', "%{$searchTerm}%") ->get();
As we know, the find () method in Laravel can be used by any user along with an array of primary keys, and it will return a set of matching records from the database. For example, $student = Students::all (); With the help of the above data, we can get the details of all the students.
After configuring the database, we can retrieve the records using the DB facade with select method. The syntax of select method is as shown in the following table. Run a select statement against the database.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With