Laravel 5.2 Moving Query to Model from Controller - php

Hi so I have this large query for a search form, And I am just wondering how I would go about moving this into the Model, I have read up on Query Scopes and so on but this is a lot more complex than just searching 1 table for 1 field and I am just so lost, Any help is appreciated!
public function index()
{
$input = Request::all();
$date = \Carbon\Carbon::now()->subMinute(30);
$query = User::rightJoin('user_profiles', 'users.id', '=', 'user_profiles.user_id');
if (isset($input ['minAge']) && $input['minAge']) {
$minAge = $input['minAge'];
$maxDate = \Carbon\Carbon::today()->subYears($minAge)->endOfDay();
}
if (isset($input ['maxAge']) && $input['maxAge']) {
if ($input['maxAge'] < $input['minAge']) {
$maxAge = $input['minAge'];
}
else {
$maxAge = $input['maxAge'];
}
$minDate = \Carbon\Carbon::today()->subYears($maxAge + 1);
}
if (isset($input['u']) && $input['u'])
$query->where('users.username', '=', $input['u']);
if (isset($input['p']) && $input['p'])
$query->where('user_profiles.postcode', '=', $input ['p']);
if (isset($input['o1']) && $input['o1'])
$query->where('users.last_online','>=',$date);
if (isset($input['o2']) && $input['o2'])
$query->whereNotNull('user_profiles.avatar');
if (isset($input ['o3']) && $input['o3'])
$query->orderBy('users.type', 'ASC');
if (isset($input ['minAge']) && $input['minAge'])
$query->whereBetween('user_profiles.dob', [$minDate, $maxDate]);
if (isset($input ['g']))
$query->whereIn('user_profiles.gender',$input ['g']);
$query->orderBy('users.last_online', 'DESC');
$users = $query->paginate(1);
return view('view', compact('users'));
}

You could do this way. Accept $input as parameter in the function in User model.
In User model, add the following code.
public static function allUsers($input)
{
$date = \Carbon\Carbon::now()->subMinute(30);
$query = User::rightJoin('user_profiles', 'users.id', '=', 'user_profiles.user_id');
if (isset($input ['minAge']) && $input['minAge']) {
$minAge = $input['minAge'];
$maxDate = \Carbon\Carbon::today()->subYears($minAge)->endOfDay();
}
if (isset($input ['maxAge']) && $input['maxAge']) {
if ($input['maxAge'] < $input['minAge']) {
$maxAge = $input['minAge'];
}
else {
$maxAge = $input['maxAge'];
}
$minDate = \Carbon\Carbon::today()->subYears($maxAge + 1);
}
if (isset($input['u']) && $input['u'])
$query->where('users.username', '=', $input['u']);
if (isset($input['p']) && $input['p'])
$query->where('user_profiles.postcode', '=', $input ['p']);
if (isset($input['o1']) && $input['o1'])
$query->where('users.last_online','>=',$date);
if (isset($input['o2']) && $input['o2'])
$query->whereNotNull('user_profiles.avatar');
if (isset($input ['o3']) && $input['o3'])
$query->orderBy('users.type', 'ASC');
if (isset($input ['minAge']) && $input['minAge'])
$query->whereBetween('user_profiles.dob', [$minDate, $maxDate]);
if (isset($input ['g']))
$query->whereIn('user_profiles.gender',$input ['g']);
$query->orderBy('users.last_online', 'DESC');
$users = $query->paginate(1);
return $users;
}
Then in your Controller, simply update the following.
With static,
public function index()
{
$users = User::allUsers(Request::all());
return view('view', compact('users'));
}
Alternatively,
public function index()
{
$user = new User;
$user->allUsers(Request::all());
return view('view', compact('users'));
}
Once you have done it this way, you can easily start to use smaller scopes. To use sample scope, you may checkout this Laravel. Use scope() in models with relation
Let me know if it works for you.

Related

what will be laravel query to sort article with maximum like

table:-
1.articles
column:= id, title, description
2.article_likes
column:= id, user_id, article_id
ArticleController.php
public function index (Request $request)
{
$articles = Article::join('article_likes', 'articles.id', '=','article_likes.article_id');
if ($request->sort == "newest") {
$articles->orderBy('id', 'DESC');
}
if ($request->sort == "popular") {
??
}
$articles = $articles->get();
dd($articles);
}
public function index (Request $request) {
$articles = Article::join('article_likes', 'articles.id', '=','article_likes.article_id');
if ($request->sort == "newest") {
$articles->orderBy('id', 'DESC');
}
if ($request->sort == "popular") {
$articles->max('like_column_name')
}
$articles = $articles->get();
dd($articles);
}
Let me know if it helps
public function index(Request $request)
{
$articles = Article::with('articleLike');
if ($request->sort == "newest") {
$articles->orderBy('id', 'DESC');
}
if ($request->sort == "popular") {
$articles->withCount('articleLike')
->orderBy('article_like_count', 'desc');
}
$articles = $articles->get();
return $this->sendResponse("Article Sorted", $articles);
}

Filter data via ajax request in Laravel

This is my function in controller
public function ajaxResponse (Request $request) {
if ($request->ajax()) {
$mat_id = $request->input('mat');
$cat_id = $request->input('cat');
$met_id = $request->input('met');
if ($cat_id != null) {
$products = Product::whereHas("categories", function ($query) use ($cat_id) {
$query->whereIn('category_id', explode(',', $cat_id));
})->get();
}
if ($mat_id != null) {
$products = Product::whereHas("productMaterial", function ($query) use ($mat_id) {
$query->whereIn('product_material_id', explode(',', $mat_id));
})->get();
}
if ($met_id != null) {
$products = Product::whereHas("productionMethod", function ($query) use ($met_id) {
$query->whereIn('production_method_id', explode(',', $met_id));
})->get();
}
if ($cat_id == null && $mat_id == null && $met_id == null) {
$products = Product::all();
}
$prod = view('partials.ajaxProducts', ['products' => $products])->render();
}
return response()->json(['prod' => $prod]);
}
all the record filtered according to $cat_id, $mat_id,$met_id
here categories and productMaterial have Many to many relations with product and productionMethod have one to many relations with the product
i want to filter data via ajax request in combination with all these three relationships
You can use:
public function ajaxResponse(Request $request) {
if ($request->ajax()) {
$mat_id = $request->input('mat');
$cat_id = $request->input('cat');
$met_id = $request->input('met');
$products = Products::query();
if ($cat_id != null) {
$products = $products->whereHas("categories", function ($query) use ($cat_id) {
$query->whereIn('category_id', explode(',', $cat_id));
});
}
if ($mat_id != null) {
$products = $products->whereHas("productMaterial", function ($query) use ($mat_id) {
$query->whereIn('product_material_id', explode(',', $mat_id));
});
}
if ($met_id != null) {
$products = $products->whereHas("productionMethod", function ($query) use ($met_id) {
$query->whereIn('production_method_id', explode(',', $met_id));
});
}
$products = $products->get();
$prod = view('partials.ajaxProducts', ['products' => $products])->render();
}
return response()->json(['prod' => $prod]);
}
public function ajaxResponse(Request $request){
if ($request->ajax()) {
$mat_id = $request->input('mat');
$cat_id = $request->input('cat');
$met_id = $request->input('met');
$products = Product::query();
if ($cat_id != null) {
$products->whereHas("categories", function ($query) use ($cat_id) {
$query->whereIn('category_id', explode(',', $cat_id));
})->get();
}
if ($mat_id != null) {
$products->whereHas("productMaterial", function ($query) use ($mat_id) {
$query->whereIn('product_material_id', explode(',', $mat_id));
})->get();
}
if ($met_id != null) {
$products->whereHas("productionMethod", function ($query) use ($met_id) {
$query->whereIn('production_method_id', explode(',', $met_id));
})->get();
}
$products = $products->get();
$prod = view('partials.ajaxProducts', ['products' => $products])->render();
}
return response()->json(['prod' => $prod]);
}

Laravel Controller - Pass a variable from function to function

So I have two functions named 'search' and 'pdfview'.
Every time I use the search function, I want to pass a query where it selects certain data to the pdfview function.
Here's my search function:
public function search(Request $request)
{
if ($request->period == 'Daily') {
$datefrom = Carbon::now()->startOfDay();
$dateto = Carbon::now()->endOfDay();
}
elseif ($request->period == 'Weekly') {
$datefrom = Carbon::now()->startOfWeek();
$dateto = Carbon::now()->endOfWeek();
}
elseif ($request->period == 'Monthly') {
$datefrom = Carbon::now()->startOfMonth();
$dateto = Carbon::now()->endOfMonth();
}
elseif ($request->period == 'Yearly') {
$datefrom = Carbon::now()->startOfYear();
$dateto = Carbon::now()->endOfYear();
}
else {
$datefrom = Carbon::parse($request->datefrom);
$dateto = Carbon::parse($request->dateto);
}
$solditems = DB::table('orders')
// ->join('orders', 'receipts.receipt_id', '=', 'orders.receipt_id')
->whereDate('orders.created_at', '>=', $datefrom)
->whereDate('orders.created_at', '<=', $dateto)
->where('status','=', 'served')
->select('orders.*', DB::raw('SUM(subtotal) as subtotal'), DB::raw('SUM(qty) as qty'))
->groupBy('item_id')
->orderBy('created_at', 'dsc')
->get();
return view('salesreports.sellingitems.index', compact('solditems'));
}
And here's my pdfview function:
public function pdfview(Request $request)
{
$solditems = DB::table('orders')
->where('status', 'served')
->select('orders.*', DB::raw('SUM(subtotal) as subtotal'), DB::raw('SUM(qty) as qty'))
->groupBy('item_id')
->orderBy('qty', 'dsc')
->get();
view()->share('solditems', $solditems);
if ($request->has('download')) {
$pdf = PDF::loadView('salesreports.sellingitems.pdf');
return $pdf->download('sellingitems-' . Carbon::now() . '.pdf');
}
return view('salesreports.sellingitems.pdf');
}
As you can see, the pdfview function has a default query for the $solditems. But I wanted that variable to come from my search function.
UPDATE: I managed to solve the problem using session.
Here's how you store with session:
session()->put('period', 'Daily');
and this is how you retrieve with session:
$period = $request->session()->get('period', 'default');
public function getSolditems()
{
if (!isset($this->solditems)) {
$solditems = DB::table('orders')
// ->join('orders', 'receipts.receipt_id', '=', 'orders.receipt_id')
->whereDate('orders.created_at','>=', $datefrom)
->whereDate('orders.created_at', '<=', $dateto)
->where('status','=', 'served')
->select('orders.*', DB::raw('SUM(subtotal) as subtotal'), DB::raw('SUM(qty) as qty'))
->groupBy('item_id')
->orderBy('created_at','dsc')
->get();
$this->solditems = $solditems;
} else {
$solditems = $this->solditems;
}
return $solditems;
}
public function search(Request $request)
{
....
$solditems = getSolditems();
....
}
public function pdfview(Request $request)
{
....
$solditems = getSolditems();
....
}
I think you can use $request->merge() method to pass $solditems data to pdfview() method from search()
public function search(Request $request)
{
....
$request->merge(['solditems'=>$solditems]);
$this->pdfview()
}
public function pdfview(Request $request)
{
$solditems = $request->get('solditems');
....
}

Laravel Pages with Categories Route Parameters

based on the example from here https://scotch.io/tutorials/simple-and-easy-laravel-routing#blog-pages-with-categories-route-parameters
I want to show entries for specific categories.
By calling this Route:
Route::get('menues/{city?}', 'PagesController#menue');
I want to show all entries for a specific city.
This is my Controller:
public function menue($city = null) {
if ($city) {
$restaurants = User::with(['articles' => function ($q){
$q->nowpublished();
}])->where('city', '=', $city)->get();
} else {
$restaurants = User::with(['articles' => function ($q){
$q->nowpublished();
}])->where('city', '!=', $city)->get();
}
return view('pages.menues')
->withRestaurants($restaurants)
->withCity($city);
}
The only thing that doesn't work is, by calling a url with a {city} that doesn't exist in the DB I want to display all entries.
With the code above this doesn't happen. I get a blank page.
How can I fix this? My guess was that the code inside my else statement displays all entries, but this isn't the case.
Do the following:
public function menue($city = null) {
$restaurants = User::with(['articles' => function ($q){
$q->nowpublished();
}]);
if(if(!is_null($city) && !is_null(City::where('name', $city)->first())) {
$restaurants->where('city', '=', $city);
}
$restaurants = $restaurants->get();
return view('pages.menues')
->withRestaurants($restaurants)
->withCity($city);
}
->where('city', '!=', $city) is the problem. If you want to get all articles, remove the condition.
Change the condition to:
if(!is_null($city) && !is_null(City::where('name', $city)->first())
Use Requests $request
public function menue(Request $request) {
if ($request->has('city')) {
I would do something like:
public function menue($city = null) {
if ($city) {
$restaurants = User::with(['articles' => function ($q){
$q->nowpublished();
}])->where('city', '=', $city)->get();
if (restaurants->count() == 0) {
$restaurants = User::with(['articles' => function ($q){
$q->nowpublished();
}])->get();
}
} else {
$restaurants = User::with(['articles' => function ($q){
$q->nowpublished();
}])->where('city', '!=', $city)->get();
}
return view('pages.menues')
->withRestaurants($restaurants)
->withCity($city);
}

How to rewrite this simple unDRY laravel method

I'm wondering how can I rewrite the following User model eloquent business logic to be a bit more DRY. I'm passing three parameters to the model, where all of them are optional, to narrow down the DB search. I'm sure there has to be a elegant way to do this, but it is beyond me at the moment.
public function guests_age($location_id, $year, $gender)
{
if($location_id && $year && $gender)
{
return Guest::select('age')
->where('location_id', '=', $location)
->where('created_at', '=', $year)
->where('gender', '=', $gender)
->get();
}
elseif($location_id && $year && !$gender)
{
return Guest::select('age')
->where('location_id', '=', $location)
->where('created_at', '=', $year)
->get();
}
elseif($location_id && !$year && !$gender)
{
return Guest::select('age')
->where('location_id', '=', $location)
->get();
}
... and so on to cover all cases...
}
Thanks for any help.
try this method
public function guests_age($location_id, $year, $gender)
{
$this->qry = Guest::select('age');
if($location_id)
{
$this->qry->where('location_id', '=', $location);
}
if($year)
{
$this->qry->->where('created_at', '=', $year)
}
if($gender)
{
$this->qry->where('gender', '=', $gender)
}
return $this->qry->get()
... and so on to cover all cases...
}
public function guests_age($args = array())
{
$columns = array('location_id', 'created_at', 'gender');
$query = Guest::select('age');
foreach($columns as $column)
{
if(!empty($args[$column]))
$query = $query->where($column, $args[$column]);
}
return $query->get();
}
//usage:
guests_age(array('location_id' => '1'));
guests_age(array('location_id' => '1', 'gender' => 'm'));
//etc..

Categories