Laravel pagination & get all - laravel

I have an API endpoint api/users that returns Users in paginated form:
public function index()
{
return User::latest()->paginate(10);
}
I also need to have access to ALL users as well, however the pagination makes this not possible.
For example I want to get all users as well using:
return User::latest()->get();
How can I use both without creating another endpoint? e.g. api/allusers

public function index($page)
{
if($page=='All')
{
return User::latest();
}
return User::latest()->paginate($page);
}

Related

How to make pagination API in laravel using POST method

Suppose i need to fetch user money transactions there are 100+ transactions in database and i need to send all the user transactions through the API to a android app, i have idea how to make using GET method but using GET method its not Dynamic.
In API i'm sorting data by 4-5 parameters in API input using post method
And i want to make this API for infinite Scrolling
And i'm using Stored Procedure for getting data
Then How can i achieve Laravel pagination in POST method?
my current response something like this
{
"Transactions"[
{
"name":"food";
"amount":100;
}
]
}
Actually, you can do it in multiple ways but the way I use most is like below
public function getTransaction(Request $request)
{
$transactions = Transactions::where('SOME-Condition', $request->Condition)->paginate(10);
$sorted = $transactions ->sortBy([
['name', 'asc'],
['age', 'desc'],
]);
return $sorted;
}
or you can also do it like this
public function getTransaction(Request $request)
{
$transactions = Transactions::where('SOME-Condition', $request->Condition)
->orderBy('abc')
->orderBy('def')
->paginate(10);
return $sorted;
}

Using latestOfMany() in Laravel

If I have a model called Placement which can have many PlacementTqLimit and I want to get the latest one, I'm assuming I can use this.
public function latestLimit()
{
return $this->hasOne(PlacementTqLimit::class)->latestOfMany();
}
And then add a custom attribute to get the value
public function getLatestLimitValueAttribute()
{
if (empty($this->latestLimit())) {
return '100';
}
return $this->latestLimit()->value;
}
However, when I dump the $this->latestLimit() I'm getting a Illuminate\Database\Eloquent\Relations\HasOne... I'm sure I shouldn't have to call return $this->hasOne(PlacementTqLimit::class)->latestOfMany()->latest(). Am I doing something wrong here?
$this->latestLimit() will return hasOne that extend query builder.
If you want to get the latest of PlacementTqLimit model just use $this->latestLimit without () or you can also use $this->latestLimit()->first()
So, to get the latest value limit, example code is:
public function getLatestLimitValueAttribute()
{
if (!$this->latestLimit) {
return '100';
}
return $this->latestLimit->value;
}

Sending different data from different method on same route - laravel 8

I am trying to get order data in order tab and profile details data in profile tab.
Is it possible to achieve ???
If Yes, then please tell me how ?
If No, then please tell me, laravel is the most advance framework of PHP, why we can't send multiple data from multiple methods in same View ?
Controller
public function GetOrders()
{
$gtord = DB::table('orders')->where('email',Session::get('email'))->get();
return view('/my-account')->with('gtord',$gtord);
}
public function ProfileEdit()
{
$data = DB::table('customers')->where('email',Session::get('email'))->first();
return view('/my-account')->with('data',$data);
}
Routes
Route::get('/my-account', 'App\Http\Controllers\CustomerController#ProfileEd');
Route::get('/my-account', 'App\Http\Controllers\CustomerController#GetOrders');
Thank you in advance
You can't have multiple routes with the same 'signature', ie method and url.
If you're just showing/hiding tabs using JS, what you can do is return the view with two variables, eg:
public function AccountView()
{
$data = DB::table('customers')->where('email',Session::get('email'))->first();
$gtord = DB::table('orders')->where('email',Session::get('email'))->get();
return view('/my-account')->with(['data' => $data, 'gtord' => $gtord]);
}
And then just use one route:
Route::get('/my-account', 'App\Http\Controllers\CustomerController#AccountView');
If the two tabs are different urls, or you're using Vue or similar you would have two distinct routes with different signatures.
First, you can't have 2 same routes with the same method. It's quite logical and necessary. Otherwise, the whole routing system would collapse.
On the other hand, you can have a function in the controller, and call the other functions to collect data.
// web.php
Route::get('/my-account', 'App\Http\Controllers\CustomerController#index');
// controller
public function index()
{
$orders = $this->getOrders();
$profile = $this->getProfiles();
return view('yourView', compact(['orders', 'profile']));
}
public function getOrders()
{
//
}
public function getProfiles()
{
//
}
BTW, it's a better practice to move custom function to models, services or traits, and keep only the functions of 7 verbs in the contoller.

A readable way to pull in a hasMany collection into a result object in the controller

Inside a resource controller I have the following show function.
public function show(Invite $invite)
{
return response($invite->jsonSerialize(), Response::HTTP_CREATED);
}
The invite model has many guests and the guest model belongs to an invite. Standard resource routes. When I query the url, I get a response like:
{
id":17,
"user_id":2,
"event_id":1,
"name":"Fred Neumann +1",
"called":0,
"emailed":0,
"invited":1,
"max_guests":2,
"created_at":"2019-05-18 21:31:07",
"updated_at":"2019-05-18 21:31:07",
"deleted_at":null
}
Now I would also like to return the guests along with the invite info. I can achieve this by modifying the show function as such:
public function show(Invite $invite)
{
// Don't remove this line:
$invite->guests = $invite->guests;
return response($invite->jsonSerialize(), Response::HTTP_CREATED);
}
This works fine but it's not obvious that it actually does anything. I could easily see myself removing it later by accident and breaking the API, hence the comment. Is there a more readable alternative?
Load the guests relationship with lazy eager loading:
public function show(Invite $invite)
{
return response($invite->load('guests')->jsonSerialize(), Response::HTTP_CREATED);
}

Passing Route Parameters to Filters when Using RESTful Controllers

I have searched around for long but nothing can quite fit my problem.
I am using RESTful controllers on my site. For some controller actions, some filters are needed and with this i do something like (i use the beforeFilter() function in the constructor):
<?php
class PostController extends BaseController {
public function __construct()
{
$this->beforeFilter('auth',array('only'=>array('getCreate','postCreate','getEdit','postEdit','postAddComment')));
$this->beforeFilter('csrf',array('only'=>array('postCreate','postEdit')));
// $this->beforeFilter('auth_post_edit', array('only'=>array('postEdit','getEdit')));
}
public function getIndex
{
$posts = Post::all();
return View::make('home')->with('posts',$posts);
}
public function getCreate()
{
return View::make('posts.create');
}
...
For the commented filter, however, it is meant to ensure that only the author of a post can edit the post, so i need to pass the post_id which is passed as a URI parameter, to the filter(or access it from the filter).
Some link showed how i can access parameters from the filter using the $route->getParameter('param') in the filter, but the problem is that because i have not even named my parameters(they are named in the controller actions), i am not able to access them from the filter using the above method.
So, how can i access route parameters from within the filter, or/and how do i name route parameters in RESTful controllers(not in their actions)?
You could use in your filter the Request::segment()
Route::filter('foo', function()
{
$param=Request::segment(2); //if the parameter is on the 2nd uri fregment.
$post=Post::find($param);
if ($post->author_id != Auth::user()->id)
{
return App::abort('404'); //or whatever
}
});

Resources