I want filter a table with several parameters. which I get from a form. it is the index function of the controller where i want to do these things. How can pass these form values to result, how to use laravel collection to apply filter to result. Sorry for a messy question and being silly.
Here is my controller code
$keyword = Input::get('keyword');
$mfs_id = Input::get('mfs_id');
$tps_id = Input::get('tps_id');
$date_start = Input::get('date_start');
$date_end = Input::get('date_end');
//values passed to view
$sales = Sale::paginate(10);
$total = Sale::sums('total_online_sale', 'discount', 'delivery_cost','sales_vat');
$mfs = Mf::lists('mfs_name', 'id');
$tps = Tp::lists('tps_name','id');
// load the view and pass the values
return View::make('sales.index')
->with('sales', $sales)
->with('total',$total)
->with('mfs',$mfs)
->with('tps',$tps);
In view file I am using a form to get $keyword, $mfs_id, $tps_id, $date_start, $date_end
view code
{{ Form::open(array('route' => array('sales.index', array('keyword' => $keyword, 'mfs_id' => $mfs_id, 'tps_id' => $tps_id, 'date_start' => $date_start, 'date_end' => $date_end)))) }}
http://laravel.com/docs/4.2/queries
$users = DB::table('users')->where('start', '>', $date_start)
->where('end', '<=', $date_end)
Or with model:
$users = Users::where('start', '>=', $date_start)
->where('end', '<=', $date_end)
Replace users with your model and add all the parameters in chainging them.
Related
Here is User Model
public function userpackages()
{
return $this->hasMany('App\UserPackages');
}
Trying to get users packages form specific month and year but it returning all records.
$users = User::with(['team', 'userpackages' => function($package) use($month,$year) {
$package->whereMonth('created_at', $month)->whereYear('created_at', $year);
}])->get();
Fetching
foreach ($users as $key => $user) {
$userpackages = $user->userpackages;
}
If I'm understanding correctly, you are filtering the eager load, but this does not affect the models returned. You need to repeat the filter using whereHas() to limit the models that are returned. In addition, functions like whereDate() can be very inefficient, especially if the column is indexed. I suggest using whereBetween() when searching a date range.
$date = Carbon::createFromFormat("Y-m", "$year-$month");
$range = [$date->startOfMonth(), $date->endOfMonth()];
$users = User::with('team')
->with(['userpackages' => fn ($q) => $q->whereBetween('created_at', $range)])
->whereHas('userpackages', fn ($q) => $q->whereBetween('created_at', $range)
->get();
To explain further:
User::with('userpackages') returns all users, each with all of their packages.
User::with(['userpackages' => 'some condition']) returns all users, each with some of their packages
User::whereHas('userpackages', 'some condition') returns some users, each with all of their packages
User::(['userpackages' => 'some condition'])->whereHas('userpackages', 'some condition') returns some users, each with some of their packages.
I am working with a rest API, and I cannot do the following query, it throws me an empty array and not the answer that I want to see:
http://localhost/project-test/public/api/contactos/buscar?name=eric&surname=almendras
controller:
public function buscar($name,$surname){
$contacto = Contacto::where('name', $name,'surname',$surname)->get();
return $contacto;
}
route: (api.php)
Route::get('contactos/buscar/{name}/{surname}','ContactosController#buscar');
You define name and surname as url params, but you include it in query string.
To access it you need to use Request class:
public function buscar(Request $request){
$name = $request->input('name');
$surname = $request->input('surname');
$contacto = Contacto::where([
'name' => $name,
'surname' => $surname
])->get();
return $contacto;
}
or change url to:
http://localhost/project-test/public/api/contactos/buscar/eric/almendras
You need to put the 2 conditions in a separate where statement:
$contacto = Contacto::where('name', $name)->where('surname',$surname)->get();
As Daniel says you need to get the parameters from the Request, you then have different options when querying the model.
You can put multiple where clauses in an array, as long as you want all the operators to be =, passed to a single where:
$contacto = Contacto::where([
'name' => $name,
'surname' => $surname
])->get();
or an array of arrays if you want to use different operators:
$contacto = Contacto::where([
['name', '=', $name],
['surname', '<>', $surname]
])->get();
or use multiple where functions
$contacto = Contacto::where('name', $name)
->where('surname', $surname)
->get();
or use Laravel's magic methods:
$contacto = Contacto::whereName($name)
->whereSurname($surname)
->get();
My model relation
return $this->hasMany('App\Models\Opportunity')->with('user');
My Attempt
$project = Project::find(1);
$$opportunities = $project->opportunities
->where('status', "confirmed");
$opportunities->each(function ($opportunity) {
return $opportunity->get('user');
});
Goal
My goal is to return the data in the following structure:
Opportunities:
Opportunity:
Status,
Amount
Currency
Name
Note that the user is a subset of the opportunity itself.
Problem
This returns a 1024 SQL error.
Ideally
It would be ideal if I can return all this information with the query itself.
Call get() method on your query to get its results first:
$oppurtunities = $project->opportunities()
->where('status', "confirmed")
->get();
You have eager loaded the user instance for each opportunity so just call $opportunity->user to return each opportunity's user:
$project = Project::find(1);
$opportunities = $project
->opportunities()
->where('status', "confirmed")
->get();
$filtered = $opportunities->map(function ($opportunity) {
return [
'status' => $opportunity->status,
'amount' => $opportunity->amount_pledged,
'currency' => $opportunity->currency,
'name' => optional($opportunity->user)->full_name
];
})->all();
I try to get data for promotion using whereIn, but the query give error.
In whereIn, if I make whereIn('category_id', [123,2323]) no error.
But when I try to get data from request($data2 = $request->category;), I cannot use with whereIn
$promotions = Promotion::with('product')->with('category')->whereHas(
'category',
function ($q) {
$data2 = $request->category;
$q->whereIn('category_id', $data2);
})
->paginate(9);
You need to use use($request)
$promotions = Promotion::with('product')->with('category')->whereHas(
'category',
function ($q) use ($request){
$data2 = $request->category;
$q->whereIn('category_id', $data2);
})
->paginate(9);
Sample data for $request->category. I return data as json and display using javascript console.log()
I am trying to set order by clause on count of field inside of larvel model.
I am using mongodb with Eloquent.
Is it even possible?
Here is a quick snippet of the query I am trying to run:
$books = Books::where(function ($query) use ($params, $res) {
$query->where('labels', 'elemMatch', array(
'genre' => $res->genre,
'outdated' => $res->false
))
->where('available', true)
->where('isSelling', true);
})
->orderBy('reviews','desc')
->paginate($params['limit']);
Reviews is an array in my database
Is it possible to order by the count of it?
you can try doing this
$books = Books::where(function ($query) use ($params, $res) {
$query->where('labels', 'elemMatch', array(
'genre' => $res->genre,
'outdated' => $res->false
))
->where('available', true)
->where('isSelling', true);
})
->orderBy('reviews','desc')
->get();
// sorting the books using sortBy or sortByDesc
$books = $books->sortByDesc(function($book){
return count(json_decode($book->reviews)); // we return the count of the reviews here
}
// get sorted ids of the books
$ids = $books->pluck('id')->toArray();
// we get the books paginated with the ids order
$books = $books->whereIn('id',$ids)
->orderByRaw(\DB::raw("FIELD(id, $ids)"))
->paginate($params['limit']);