Knp Paginator doesn't works with Query - paginator

I am settting up knp paginator, my composer is set to "knplabs/knp-paginator-bundle": "2.3.*" however It is not working for Query object.
Here is my query:
public function getCommentariesByUser(User $user) {
$qb = $this->createQueryBuilder('c');
$qb->innerJoin('c.item', 'i');
$qb->andWhere($qb->expr()->eq('i.user', ':user'))
->setParameter(':user', $user);
$qb->andWhere($qb->expr()->neq('c.user', ':user1'))
->setParameter(':user1', $user);
return $qb->getQuery();
}
How I am calling it in my action:
public function commentariesAction($page) {
$user = $this->getUser();
$commentaryRepository = $this->getDoctrine()->getRepository('My\MyBundle\Entity\Commentary');
$query = $commentaryRepository->getCommentariesByUser($user);
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$query,
$page/*page number*/,
15/*limit per page*/
);
return array('pagination' => $pagination);
}
It simply doesn't show results, however If I put $query->execute() It works. What's wrong?

Currently this is possible to use next combination of paginator packages for code above to work:
"knplabs/knp-components": "1.2.1",
"knplabs/knp-paginator-bundle": "~2.3"

Related

Where can I put paginate()?

I am trying put paginate(10) to add a pagination later, but when I added it it gives me this error:
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$product
Here is my controller where I want add the pagination(10):
public function index()
{
$user_id = auth()->user()->id;
$user = User::find($user_id);
return view('your')->with('product', $user->product);
}
I did try this:
public function index()
{
$user_id = auth()->user()->id;
$user = User::find($user_id)->paginate(10);
return view('your')->with('product', $user->product);
}
How can I avoid the undefined property error?
Actually find function is used for getting only 1 result and you are applying pagination on that which is resulting into an error.
You might be wanting the products data to be paginated, For that do like this
public function index()
{
$user_id = auth()->user()->id;
$user = User::find($user_id)->product()->paginate(10);
return view('your')->with('product', $user);
}

can't store when using [IF] in eloquent din't work

I need to Store when have data in [Booking] but din't store anything to [scan]
public function store(Request $request, $id){
$event = event::findOrFail($id);
$booking = booking::where('student_id',Auth::user()->student_id)
->where('name',Auth::user()->name)
->where('event_id',$event->id);
if($booking!=NULL){
$requestData = $request->all();
scan::create($requestData);
return redirect('event/' . $event->id .'/scan');
return view('event.scan', compact('event','scan','booking'));
}else{
return redirect('event/' . $event->id .'/scan');
}
}
but when using $booking==null
it store anything can't check in booking
Your query is incomplete. It lacks of any final query method like get(), first() or exists()
Also you have two return statements inside the if block. Only the first will be executed, the second one will be ignored.
The correct code should be like this:
public function store(Request $request, $id){
$event = event::findOrFail($id);
$booking = booking::where('student_id',Auth::user()->student_id)
->where('name',Auth::user()->name)
->where('event_id',$event->id)
->get(); // look this line
if($booking!=NULL){
$requestData = $request->all();
scan::create($requestData);
return redirect('event/' . $event->id .'/scan'); // I think this should not be here, right?
return view('event.scan', compact('event','scan','booking')); // this is being ignored.
}else{
return redirect('event/' . $event->id .'/scan');
}
}
you can update your method like so. its much clearer and readable (i think anyway).
public function store(Request $request, $id)
{
//use first to get a booking or use get() for collections of booking
$booking = Booking::where('student_id', auth()->user()->student_id)
->where('event_id', $id)
-first();
if (is_null($booking)) {
return redirect('event/' . $id . '/scan');
}
return view('event.scan', [
'event' => Event::findOrFail($id),
'scan' => Scan::create($request->all()),
'booking' => $booking
]);
}
Hope this helps
Cheers

laravel & vuejs: Builder could not be converted to string

this is my search function in users controller
public function search()
{
if( $search = \Request::get('q') ){
$users = User::where( function($query) use ($search){
$query->where('name','LIKE',"%$search%");
});
}
return $users;
}
this is the vuejs code .Fire is new instance of vuejs that i created in app.js
Fire.$on('searching',() => {
let query = this.$parent.search; // query parent(app.js) for 'search'
axios.get('api/findUser?q='+query)
.then((data) => {
this.users = data.data;
})
});
You've constructed a query, but you haven't actually run it until you call ->get() on it.
return $users->get();

why i can't call name from table food?

public function orderlist(Request $request){
$id = $request->id;
$data['order'] = Order::where('shop_id',$id)->orderBy('id')->get();
foreach($data['order'] as $orders){
$orders->shop = Shop::where('id',$orders->shop_id)->first();
$orders->food = Food::where('id',$orders->food_id)->get();
}
return $orders->food->name;
return view ('administrator.users.list_order.index',$data);
}
If you set up proper Eloquent relationships, this code could be rewritten like so:
public function orderlist(Request $request, Shop $shop){
$orders = $shop->orders()->with(['food'])->get();
return view ('administrator.users.list_order.index',compact('orders'));
}
Check out the docs here: https://laravel.com/docs/5.7/eloquent-relationships

Laravel Excel - Select columns to export

I'm using Laravel Excel from maatwebsite but i have a problem with export data to xls file. I have this query but i don't need to show all columns in the xls file but i need to select all this columns to do operations before download the file. In my select i have 8 columns but in my headers i just have 7 to show but this doesn't work because the 8ª column appears too.
MY FUNCTION:
public function toExcel($id) { $b = Budget::find($id);
$budget = Budget_Item::join('budgets', 'budget__items.id_budget', '=', 'budgets.id')
->join('items_sizes', 'budget__items.id_itemSize', '=', 'items_sizes.id')
->join('items', 'items_sizes.id_item', '=', 'items.id')
->join('material_types', 'items_sizes.id_materialType', '=', 'material_types.id')
->select('items.reference AS Referência', 'items.name AS Descrição', 'items_sizes.size AS Tamanho', 'material_types.material_type AS Material', 'budget__items.amount AS Quantidade', 'items_sizes.unit_price AS Val.Unitário', 'budget__items.price AS Val.Total', 'budget__items.purchasePrice')
->where('id_budget', '=', $id)
->get();
$budgetUpdate = [];
$budgetUpdate[] = ['Referência', 'Descrição', 'Tamanho', 'Material', 'Quantidade', 'Val.Unitário', 'Val.Total'];
foreach ($budget as $key)
{
if ($key->purchasePrice > 0)
{
$key->unit_price = $key->purchasePrice;
}
$budgetUpdated[] = $key->toArray();
}
Excel::create('Proposta_'.$b->reference, function($excel) use($budgetUpdated)
{
// Set the title
$excel->setTitle('Proposta');
$excel->sheet('Sheetname', function($sheet) use($budgetUpdated)
{
$sheet->fromArray($budgetUpdated, null, 'A1', false, true);
});
})->download('xls');}
How can i solve that?
Thank's
Tested on Laravel excel 3.1 docs
on controller
public function exportAsCsv()
{
return Excel::download(new MyExport, 'invoices.xlsx');
}
on MyExport, look at the map function
class MyExport implements FromCollection, WithHeadings, WithMapping{
public function collection(){
return MyTable:all();
}
// here you select the row that you want in the file
public function map($row): array{
$fields = [
$row->myfield2,
$row->myfield1,
];
return fields;
}
}
also check this
For what its worth I ran into a similar issue and didnt find much in terms of a fix so heres my solution.
1. I query the DB in the callback and get all the data I need.
2. I then go over the collection and create a new array on each iteration and assign a value & header. Works great for picking out columns from a model
Excel::create('User List Export', function($excel) {
$excel->sheet('Users', function($sheet) {
$email = yourModelGoesHere::all();
foreach ($email as $key => $value) {
$payload[] = array('email' => $value['email'], 'name' => $value['name']);
}
$sheet->fromArray($payload);
});
})->download('xls');
You can try this way.
$user_id = Auth::user()->id
Excel::create('User', function($excel) use ($user_id){
$excel->sheet('Sheet', function($sheet) use($user_id){
$user = User::where('user_id', $user_id)->select('name', 'email', 'role', 'address')->get();
});
})->export('xls');
return redirect('your route');

Resources