I am trying to send posts to Laravel Api. and I want to paginate them and also arrange them according to the latest. But I am gettting an error Method Illuminate\Database\Eloquent\Collection::paginate does not exist. in file
Here is my Api Code
public function index()
{
$posts = Post::with('comment', 'user')
->latest()
->get()
->paginate(5);
return response()->json([
'status'=>200,
'posts'=>$posts
]);
}
Kindly help. Thank you
You don't need to call the get method, this is enough:
$posts = Post::with('comment', 'user')
->latest()
->paginate(5);
Related
I am using Laravel Framework 8.62.0 and PHP 7.4.20.
I get the following error:
Call to undefined method Illuminate\Database\Eloquent\Builder::links() (View: /home//Code/test_project/resources/views/index.blade.php)
I have a view that has uses 3 simple filters. To display the view via get I use the following:
public function getSearchView()
{
try {
$con = 'mysql_prod';
// search results
$items = Item::on($con)->select(['items.name AS item_name', 'items.slug', 'items.id AS item_id', 'item_details.sticker_number', 'item_details.section', 'item_details.type', 'collections.name AS collections_name', 'collections.sport_type', 'collections.league', 'collections.year as collections_year', 'images.file_name'])
->leftJoin('item_details', 'items.id', '=', 'item_details.items_id')
->leftJoin('collections', 'items.collections_id', '=', 'collections.id')
->leftJoin('images', 'images.items_id', '=', 'items.id')
->limit(500)
->paginate(10);
// filter field
$condition = Condition::on($con)->select(['id', 'name AS condition_name'])
->distinct()
->get();
$collection = Collection::on($con)->select(['id', 'name AS collection_name'])
->distinct()
->orderBy('collection_name', 'ASC')
->get();
return view('index', compact('items'));
} catch (\Exception $e) {
Log::error($e);
report($e);
}
}
To filter the view I use:
public function postFilter(Request $request)
{
try {
$con = 'mysql_prod';
//##################################
// QUERY - SEARCH RESULTS
//##################################
$items = Item::on($con)->select(['items.name AS item_name', 'items.slug', 'items.id AS item_id', 'item_details.sticker_number', 'item_details.section', 'item_details.type', 'collections.name AS collections_name', 'collections.sport_type', 'collections.league', 'collections.year as collections_year', 'images.file_name'])
->leftJoin('item_details', 'items.id', '=', 'item_details.items_id')
->leftJoin('collections', 'items.collections_id', '=', 'collections.id')
->leftJoin('images', 'images.items_id', '=', 'items.id');
// collection
if(!is_null($request->select_collection_field)) $items->where('collections.id', '=', intval($request->select_collection_field));
// FILTER field
if(!is_null($request->select_filter_field)) {
if($request->select_filter_field === "select_all") $items->orderBy('item_name', 'desc');
if($request->select_filter_field === "publishing_year") $items->orderBy('collections_year', 'desc');
}
// query database
$items->limit(500)->paginate(10);
//##################################
// FILTERS
//##################################
$condition = Condition::on($con)->select(['id', 'name AS condition_name'])
->distinct()
->get();
$collection = Collection::on($con)->select(['id', 'name AS collection_name'])
->distinct()
->orderBy('collection_name', 'ASC')
->get();
return view('index', compact('items', 'condition', 'collection'));
} catch (\Exception $e) {
Log::error($e);
report($e);
}
}
In my web.php I have the two endpoints:
Route::get('/', [SearchController::class, 'getSearchView'])->name('/');
Route::post('postFilter', [SearchController::class, 'postFilter']);
In my view I use the pagination of laravel:
{!! $items->links('vendor.pagination.default') !!}
Any suggestions why I get the above error and how to fix it?
I appreciate your replies!
$items is currently a Query Builder instance. This object wont change, it will continue to be a Query Builder instance. When you execute a query from a Query Builder you get a returned result, and that is what you need to be passing to your view. You could reassign $items to this result easily:
$items = $items->limit(500)->paginate(10);
Now $items is the Paginator instance because you reassigned that variable to the result of the paginate call.
public function boot()
{
Paginator::defaultView('view-name');
Paginator::defaultSimpleView('view-name');
}
add this code to AppServiceProvider. I hope it will work.
Just wondering where to position the Laravel's pagination() here in my query() in order for it to work. I tried adding it at the end of $all_procedures:
public function fetchprocedure(Request $search_procedure) {
$filter_procedure = $search_procedure->input('search_procedure');
$all_procedures = HmsBbrKnowledgebaseProcedure::query()
->when(is_null($filter_procedure), function ($query) {
$query->where('bbr_procedure_id', '>=', 1);
})
//iLike is case insensitive
->when(!empty($filter_procedure), function ($query) use ($filter_procedure) {
$query->where('procedure_name', 'iLIKE', "%$filter_procedure%");
})
->orderBy('bbr_procedure_id', 'ASC')
->get()
->paginate(10);
return response()->json([
'all_procedures' => $all_procedures,
]);
}
UPDATE:
tried a solution given by an answer. Got rid of get(); but my error this time is:
Just instead of having:
->get()
->paginate(10);
Do
->paginate(10);
That will automatically get 10 results and paginate it taking into account the current page.
I want redirect url from /topic/{title} to /topic/{category}/{title}.
So I try to registered this in routes:
Route::get('/topic/{title}',function(){
return redirect()->action('/topic/{category}/{title}','DetailController#index');
});
But I got error
Action App\Http\Controllers/topic/{category}/{title} not defined.
Anyone can help me about the routes?
Thanks for advance.
This is my Controller
class DetailController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index($section=0,$title = 0)
{
$detail = DB::table('t_artikel')
->join('t_section', 't_section.id_section', '=', 't_artikel.id_section')
//->join('t_kolom', 't_kolom.id', '=', 't_artikel.penalar')
->where('publish', '=', 'Y')
->where('parent_id', '=', 0)
->where('tgl_pub', '<=', date('Y-m-d H:i:s'))
->where('t_artikel.urltitle', '=', $title)
->select('t_artikel.*', 't_section.*', 't_artikel.urltitle as urlartikel')
->first();
$kategori = DB::table('t_section')
->where('id_supsection', '=', 0)
->where('status', '=', 1)
->orderBy('position', 'asc')
->whereNotIn('id_section', [34])
->select('t_section.*')
->get();
$page = 'Detail';
return view ('detail.detail',
['detail' => $detail,
'kategori' => $kategori,
'page' => $page
]);
}
As per the documentation,
If your controller route requires parameters, you may pass them as the second argument to the action method
So, you need to pass the parameters like this:
return redirect()->action(
'DetailController#index', ['category' => <enter_value>, 'title' => <enter_value>]
);
I would suggest you to use 2 routes and 2 controllers. One handles the details of the topic and the other one handles the redirect of the "old" url.
For example: the user will visit "/topic/title" that is handled by a controller that will recognize topic and category, then will use the
public function handleTopic($title){
// the code here will recognize topic and category
// and will just provide the stuff to show the right page
// in the end will redirect to that controller
return redirect()->action('DetailController#index', ['category' => $category, 'title' => $title]);
}
public function index($stuffYouNeed){
// retrieve the rest of data you need to show the page
// you already know the title and category (cause of previous controller)
// in the end return the view with data
return view ('detail.detail',['data' => $data]);
}
In your routes you'll have to add one route and edit the existing one like:
Route::get('topic/{title}', 'DetailController#handleTopic')->name('handleTopic');
Route::get('topic/{category}/{title}', 'DetailController#index')->name('showTopic');
It's not tested cause atm i don't have a laravel env set up in local. But i think it should work. Let me know
Edit: I forgot to explain why you see the error
Action App\Http\Controllers/topic/{category}/{title} not defined.
You are using the redirect incorrectly
Route::get('/topic/{title}',function(){
return redirect()->action('/topic/{category}/{title}','DetailController#index');
});
You can only provide an action controller, not a route. And the destination route have to exist. So the right use is:
return redirect()->action('Controller#action');
Anyway, you should split logic from routes. You have controllers for that... even for really short blocks of code. It will keep everything in order and clear. In your route file you should have ONLY routes.
Solved, I found my way after modified. and this is the code:
Route::get('/topik/{title}',function($title){
$article = DB::table('t_artikel')
->join('t_section', 't_section.id_section', '=', 't_artikel.id_section')
->where('publish', '=', 'Y')
->where('parent_id', '=', 0)
->where('tgl_pub', '<=', date('Y-m-d H:i:s'))
->where('t_artikel.urltitle', '=', $title)
->select('t_artikel.*', 't_section.urltitle as urltitlesec', 't_artikel.urltitle as urlartikel')
->first();
$kategori = $article->urltitlesec;
return redirect("/topik/{$kategori}/{$title}");
});
If you want to redirect to a URI, then don’t use redirect()->action(); use redirect()->to() instead:
Route::get('/topic/{title}', function ($title) {
$category = ''; // Get category some how
return redirect()->to("/topic/{$category}/{$title}");
});
I have two routes for web middleware in my laravel app listed below:
Route::get('package/{slug}','GetPublicController#tourDetail')
->name('single');
And
Route::get('/trips/{category}','GetPublicPageController#getBycategory')
->name('getBycategory');
The first route works well but second route doesn't. The second route is in conflict with the first route as it tries to get view of first route, causing error and app to breakdown.
Method for 1st route:
public function tourDetail($slug)
{
$tour = Tour::where('slug', '=', $slug)
->first();
$itineraries = Itinerary::where('tour_id','=', $tour->id)
->orderBy('id', 'asc')->get();
$depature_dates = $tour->datePrice()->FixedDates($tour->id, date('m'),date('Y'))->get();
return view('public.tour.tour-detail')
->withTour($tour)
->withItineraries($itineraries)
->withDepatures($depature_dates);
}
And method for 2nd route
public function getByCategory($category)
{
$query = Tour::whereHas('category', function($r) use($category) {
$r->where('tcategories.name','=', $category);
});
return view('public.pages.category-list')
->withResults($query);
}
It would be very helpful if anyone could suggest the best approach to resolve this issue.
Thank you.
You have to call ->get() on the query in getByCategory.
I'm using tabs but same controller, different methods. How to return values to different views with same route?
In /users, get value from db via BuyerSellerController#buyers method for buyer.
Route::get('users','BuyerSellerController#buyers');
In /users as well, get value from db via BuyerSellerController#sellers method for seller.
Route::get('users','BuyerSellerController#sellers');
//BuyerSellerController
public function buyers()
{
$buyerSeller = DB::table('buyerseller')
->where('buyerseller','=','Buyer')
->pluck('id');
$buyers = DB::table('users')
->where('buyerseller','=',$buyerSeller)
->get();
return View::make('pages.users')->with('buyers', $buyers);
}
public function sellers()
{
$buyerSeller = DB::table('buyerseller')
->where('buyerseller','=','Seller')
->pluck('id');
$sellers = DB::table('users')
->where('buyerseller','=',$buyerSeller)
->get();
return View::make('pages.users')->with('sellers', $sellers);
}
//users.blade.php
Then I got this error:
Undefined variable: sellers (View: ...)
compact saved my life! :D
public function index()
{
/* buyers */
$buyerSeller = DB::table('buyerseller')
->where('buyerseller','=','Buyer')
->pluck('id');
$buyers = DB::table('users')
->where('buyerseller','=',$buyerSeller)
->get();
/* sellers */
$buyerSeller = DB::table('buyerseller')
->where('buyerseller','=','Seller')
->pluck('id');
$sellers = DB::table('users')
->where('buyerseller','=',$buyerSeller)
->get();
return View::make('pages.users', compact('buyers', 'sellers'));
}