Reputation: 5859
I have this code below which searches for tags that the first letter is queried against, so the query is like this myurl.com/tags?alpha=E but I want to query things that start with a number how could I query the database when the alpha could use the hash code # representing that it's a number to be queried and return tags that start with a number, checkout my code below
public function index()
{
//
$tags = null;
if(Input::get('alpha') != null)
{
// alpha could be A,B,C,D,E etc
$tags = Tag::where('name', 'Like', Input::get('alpha') . '%')->orderBy('name', 'asc')->paginate(40);
}
else
{
$tags = Tag::orderBy('name', 'asc')->paginate(40);
}
return View::make('tags.index')->with(compact('tags'));
}
Upvotes: 0
Views: 1074
Reputation: 25100
You can do like this:
public function index() {
$tags = null;
$alpha = Input::get('alpha');
if ( preg_match("/^[a-zA-Z]$/", $alpha) ) {
$tags = Tag::where('name', 'Like', Input::get('alpha') . '%')->orderBy('name', 'asc')->paginate(40);
} else if ( $alpha == "#" ) {
$tags = Tag::whereRaw("name regexp '^[0-9]'")->orderBy('name', 'asc')->paginate(40);
} else {
$tags = Tag::orderBy('name', 'asc')->paginate(40);
}
return View::make('tags.index')->with(compact('tags'));
}
Note that: to send # character you must use '%23' for alpha value instead of '#' (myurl.com/tags?alpha=%23)
Upvotes: 1