I have this on my model Scholar
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Scholar extends Model {
protected $primaryKey = 'scholar_id';
protected $fillable = ['ngo_id','scholar_lname','scholar_fname','scholar_image','scholar_nickname','scholar_cityAddress','scholar_permaAddress','scholar_birthday','scholar_placebirth','scholar_age','scholar_gender','scholar_email','scholar_contact'];
}
then this is on my Controller
$scholars = new Scholar; <------
if(Input::get('age_from'))
$scholars->where('age', '=', Input::get('age_from'));
$scholars->get();
return $scholars;
I want to initiate this, but when I try the $scholars = Scholar::all();
I cant use ->get()
anymore;
Anyway how to do this optional where
?
You can use newQuery;
$scholars = (new Scholar)->newQuery();
if(Input::get('age_from')) {
$scholars->where('age', '=', Input::get('age_from'));
}
return $scholars->get();
Probably this is not the best way to do it but it works
Try something like:
$scholars = Scholar::where('id','>',0); //Assuming you have an autoincrement id in your table
if(Input::get('age_from'))
$scholars->where('age', '=', Input::get('age_from'));
$scholars->get();
return $scholars;
If you need to get all scholars anyway you can get all rows in a collection with just one query:
$allScholars = Scholar::all();
And then you can get any data from the collection:
$scholars = $allScholars->where('age', '=', Input::get('age_from'));
Now you all scholars in $allScholars
collections and scholars of specified age in $scholars
one.