Hi when I'm doing a search for a order, then I can't get my orders paginated (5 orders per page)..
I have also recorded myself to show you the problem that I currently have:
link: https://www.youtube.com/watch?v=sffTI6adS7A&feature=youtu.be
This is the code that I'm using:
OrdersController.php:
public function post_search()
{
$keyword=Input::get('keyword');
if(empty($keyword))
return Redirect::route('user.orders.index')->with('error_search', 'Er was geen zoekterm ingevuld, probeer het nog eens.');
//$orders = Order::with('client')->get();
//$orders= new stdClass;
//$orders->foo=Order::search($keyword)->paginate(5);
$orders=Order::search($keyword);
$msg="";
if (!count($orders)) {
$msg="There were no orders found.";
}else{
$msg="There were orders found";
}
$orders = Paginator::make($orders, count($orders), 5);
foreach( $orders as &$order){
//we initialize ordertask
$order->ordertask = Ordertask::where('id_order', '=', $order->id)->get();
}
return View::make('user.orders.index', compact('orders', 'msg'));
}
Order.php:
public static function search($keyword){
DB::connection()->getPdo()->quote($keyword);
$result = DB::Select(DB::raw('SELECT orders.*, tasks_x.task_all
FROM orders LEFT JOIN (SELECT GROUP_CONCAT(tasks.task_name SEPARATOR ",")
AS task_all, ordertasks.id_order
FROM tasks JOIN ordertasks
on ordertasks.id_task = tasks.id GROUP BY ordertasks.id_order) as tasks_x
ON tasks_x.id_order = orders.id WHERE orders.order_name
LIKE "%'.$keyword.'%" OR tasks_x.task_all LIKE "%'.$keyword.'%"'));
return $result;
}
What have I tried:
I have changed the form action to GET and POST, but that didn't work.
Can someone maybe help me, please?
You can't paginate a raw query using laravel paginator. You can only paginate queries made with the query builder or an Eloquent model.
You would have to manually paginate the query (using LIMIT in your query), and then use Paginator::Make() to show the paginator view. Also, you would have to retrieve the number of items with a different query, as using count() over the results array would give you the number of results in that page (Generally, the page size, except for last page)
Other option would be to change from that raw query to a query made using the query builder, but laravel doesn't recommends this as you're using "Group By" and the official docs says:
Note: Currently, pagination operations that use a groupBy statement cannot be executed efficiently by Laravel. If you need to use a groupBy with a paginated result set, it is recommended that you query the database manually and use Paginator::make.
Official Doc
This is what I do in every pagination search:
Controller
$query = new Product();
//dynamic search term
if (Input::has('code')){
$term = Input::get('code');
$term = trim($term);
$term = str_replace(" ", "|", $term);
$query = $query->whereRaw("itemcode regexp '".$term."'");
if (Input::has('description')){
$term = Input::get('description');
$term = trim($term);
$term = str_replace(" ", "|", $term);
$query = $query->whereRaw("itemcode regexp '".$term."'");
}
//if there are more search terms, just copy statements above
$products = $query->paginate(50); //get 50 data per page
$products->setPath(''); //in case the page generate '/?' link.
$pagination = $products->appends(array('code' => Input::get('code'),
'description' => Input::get('description')
//add more element if you have more search terms
));
//this will append the url with your search terms
return redirect('product')->with('products', $products)->with('pagination', $pagination);
View
<div class="panel panel-default">
<div class="panel-heading">
<h6 class="panel-title"><i class="icon-paragraph-justify"></i> Striped & bordered datatable</h6>
</div>
<div class="datatable">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>#</th>
<th>Item Code</th>
<th>Description</th>
</tr>
</thead>
<tbody>
#foreach($products as $key)
<tr>
<td>{{ $key->id}}</td>
<td>{{ $key->itemcode }}</td>
<td>{{ $key->description }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
{!! $products->render() !!}
Related
I'm not using eloquent, my models are like this.
class drivers extends Model
{
}
I want to display records of all drivers ( one record in each row )
My driver table has field (driver_id,name,tyre_id)
My tyre table has field (id, title)
My bank table has field (id, driver_id, bank)
I want my record to be like this...
Driver Id, Name, Bank Details, Tyre Title
100000111, Ayer, Available, GO
.. so on
For bank details if driver_id has a record in bank table, it should display available otherwise N/A.
$drivers= Drivers::get();
$myarray = ();
foreach ($drivers as $d){
$bank = Bank::where('driver_id',$d->driver_id)->first();
$tyre = Tyre::where('id',$d->tyre_id)->first();
$myarray[] = $d->driver_id;
$myarray[] = $d->name;
$myarray[] = isset($bank) ? "available" ; '';
$myarray[] = $tyre->title;
}
This is what i have tried, I'm to new to laravel, how can i achieve this in laravel or using query like DB Table?
Laravel offers two very useful tools for performing database operations eloquent and query builder. It is advisable to work as much as possible with eloquent and their relationships as it facilitates much of the common operations that we normally need to perform.
Now, if you want to make more complex queries you can use query builder, also, an example of your case using query builder would be something like this:
In your controller you make the query and pass the data to view:
$data = DB::table('driver')
->leftJoin('bank', 'bank.driver_id','=', 'driver.driver_id')
->join('tyre', 'tyre.id','=', 'bank.tyre_id')
->select('driver.driver_id as id',
'driver.name',
'bank.id as bank_id',
'tyre.title')
->groupBy('driver.driver_id')
->get()
And in your view you can use a foreach loop to display the data (and you can use a conditional to display the bank field):
<table>
<thead>
<tr>
<th>Driver ID</th>
<th>Name</th>
<th>Bank Detail</th>
<th>Tyre Title</th>
</tr>
</thead>
<tbody>
#foreach($data as $item)
<tr>
<td>{{ $item->id }}</td>
<td>{{ $item->name }}</td>
<td>{{ isset($item->bank_id) ? "availible":"N/A" }}</td>
<td>{{ $item->title }}</td>
</tr>
#endforeach
</tbody>
</table>
likewise I recommend you read the documentation of eloquent and try to use it.
https://laravel.com/docs/5.5/queries
https://laravel.com/docs/5.5/eloquent
The Good way to Solve this is laravel relations
here the link
laravel documentation
Select your driver table as base table and use relations to get the other table fields;
array_push() function to push values to array
Another way is using DB Facade with joins: Like this:
$users = DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.*', 'contacts.phone', 'orders.price')
->get();
Is it possible to add two integers from the database inside a blade?
To give a scenario, I have a controller that compacts a collection of orders table.
$solditems = DB::table('orders')
->where('status', 'served')
->orderBy('id')
->get();
return view('salesreports.sellingitems.index', compact('solditems'));
And I used those like this in my blade.
<table class="table table-hover">
<tr>
<th>ID</th>
<th>Item</th>
<th>Sales</th>
</tr>
<thead>
</thead>
<tbody>
#forelse($solditems as $solditem)
<tr>
<td>{{$solditem->id}}</td>
<td>{{$solditem->item}}</td>
<td>{{$solditem->subtotal}}</td>
</tr>
#empty
#endforelse
</tbody>
</table>
Now, what I want to do is to combine an item that has same item names or $solditem->item while adding up there subtotals.
For example;
ID #1 Apple = 50
ID #2 Apple = 80
Will become this;
ID #1 Apple = 130
I tried using groupBy on query builder so an item with same name will only show once, but I'm having problems designing an algorithm adding up the subtotal.
Try this one,
This gives you sum of cost with same item name for all items.
$solditems = DB::table('orders')
->where('status', 'served')
->select('orders.*',DB::raw('SUM() as total'))
->groupBy('orders.item')
->orderBy('id')
->get();
You could take advantage of Laravel's collection methods. You can use the GroupBy method to create grouped subarrays by product name and foreach of those group using the Sum method return the sum of the total column.
I'm using Laravel and the Eloquent ORM that it provides but I'm struggling to select the data I need. I have 3 Models
House
Occupants
Job
A house can have multiple occupants and I can easily get these using the following.
$house= House::find($house_id);
$occupants = $house->occupants()->where('active', 1)->get();
This works nicely but I also want to select the job of each occupant. I've got this as a one to one relationship but the jobs are in a seperate table.
Is there a way to also select the related job for each occupant from the jobs table efficiently? I'm guessing it would be something like this
$occupants_and_jobs = $house->occupants()->where('active', 1)->job()->get();
You could just try what you are suggesting and see what happens.
You can also do some eager loading of the relationships
$house = House::with(["occupants","occupants.job"])->find($house_id);
foreach ($house->occupants as $occupant) {
print_r($occupant->job);
}
As #AlexeyMezenin if you need to constrain the relationship then you need to (as the docs suggest under Constraining Eager Loads) do:
$house = House::with(["occupants" => function ($query) {
$query->where("active","=",1);
},"occupants.job"])->find($house_id);
foreach ($house->occupants as $occupant) {
print_r($occupant->job);
}
Now the fine-print: Laravel will include "with" relationships in the order it finds them and also include all intermediate relationships of the nesting, e.g. ::with("occupants.job") implies ::with(["occupants","occupants.job"]) however if you already have set a previous relationship then it is maintained (which is how this works). occupants will not be overwritten when occupants.job is set.
This query will load all occupants with active = 1 and their jobs:
House::with(['occupants' => function($q) {
$q->where('active', 1);
}, 'occupants.job'])->find($house_id);
Complete way to to search data from different tables in laravel:
Route:
Route::get('/systems/search', 'SearchController#search')->name('project-search');
Try this way in your searchController:
public function search(Request $request)
{
$data = DB::table('projects as p')->select('p.*','u.first_name', 'u.last_name')
->join('users as u','p.user_id','=','u.id');
if( $request->input('search')){
$data = $data->where('p.title', 'LIKE', "%" . $request->search . "%")
->orWhere('p.description', 'LIKE', "%" . $request->search . "%")
->orWhere('u.first_name', 'LIKE', "%" . $request->search . "%")
->orderBy('p.created_at', 'desc');
}
$data = $data->paginate(16);
return view('systems.search', compact('data'));
}
And receive those data in your blade like this way:
<div class="col-md-8">
<h3>List of Results</h3>
<table class="table table-striped">
<tr>
<th>title</th>
<th>description</th>
<th>creator</th>
<th>category</th>
</tr>
#foreach($data as $search)
<tr>
<td>{{ $search->title }}</td>
<td>{{ $search->description }}</td>
<td>{{ $search->first_name }}</td>
</tr>
#endforeach
</table>
{{ $data->appends(request()->except('page'))->links() }}
</div>
search box input field:
<div class="input-group input_search" style="width: 100%">
<input style="border-radius: 20px" type="text" class="form-control search"
placeholder="Search" aria-describedby="basic-addon2" name="search" id="search"
value="{{Request::get('title')}}">
As I am developing a project in larawel 5.3. and I am using two tables in database first users ans second points you can see my points table structure in this link.
I want to get user id in laravel 5.3 controller with Auth::user()->id but it creates error their
So when a transection occurs. it is saved in points table getting assousiated with user_id so net points of a user can can be taken as using folloing query
$points = Points::select(DB::raw("sum(p_add)-sum(p_less) as Total"))->where('user_id', Auth::user()->id)->first();
now I am goin to gett all data of users in a single admin page. so I am using following code in controller
public function users_list()
{
$ptitle = "Website Users";
$pdesc = "";
$total_users = User::count();
$users = User::select('*')->orderby('created_at', 'desc')->get();
return view('admin.all-users-list',
['ptitle' => $ptitle,
'pdesc' => $pdesc,
'users' => $users,
'total_users' => $total_users,
]);
}
And folloing foreach loop to fetch users data in view page
<table class="table table-hover">
<tbody><tr>
<th>ID</th>
<th>User Name</th>
<th>Email</th>
<th>Country</th>
<th>Date</th>
<th>Points</th>
</tr>
<?php foreach ( $users as $u ){ ?>
<tr>
<td>{{ $u->id }}</td>
<td>{{ $u->user_name }}</td>
<td>{{ $u->email }}</td>
<td>{{ $u->country }}</td>
<td>{{ $u->created_at }}</td>
<td>????</td>
</tr>
<?php }?>
</tbody></table>
and result on view is as in this image
now I dont now that how can I fetch net points from points table for every user. please provide me some help to solve this issue.
you can make public function and call it every loop in foreach loop. Or create static function on the Points model class to get points for every user by using user_id as argument.
Put getUserPoints on Points model class
public static function getUserPoints($userId){
$points = self::select(DB::raw("sum(p_add)-sum(p_less) as Total"))
->where('user_id', $userId)->first();
if( $points != null ){
return $points->Total;
}
return 0;
}
}
And you can call it every loop as {{ \App\Points::getUserPoints($u->id) }}
I am trying to implement pagination in laravel and got following error
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$name
Here is my controller function
public function showTags($id)
{
$tag = Tag::find($id)->paginate(5);
// when lazy loading
$tag->load(['posts' => function ($q) {
$q->orderBy('id', 'desc');
}]);
return view('blog.showtags')->withTag($tag);
}
Here is the Tag Model
class Tag extends Model
{
public function posts()
{
return $this->belongsToMany('App\Post');
}
}
The Tag and Post model has belongsToMany Relationship so there are many posts under the specific tag and my aim is to iterate all posts under the specific tags descending order of post and also to implement pagination in that page.
Here is the code for showtags view
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Title</th>
<th>Tags</th>
</tr>
</thead>
<tbody>
<?php $count = 1; ?>
#foreach($tag->posts as $post)
<tr>
<th>{{ $count++ }}</th>
<th>{{ $post->title }}</th>
<th>#foreach($post->tags as $tag)
<span class="label label-default">{{ $tag->name }}</span>
#endforeach
</th>
</tr>
#endforeach
</tbody>
</table>
//Here is the code i used for pagination in view
<div class="text-center">
{!! $tag->posts->links() !!}
</div>
If anybody know how to do this please respond. Thanks in advance.
I solve the problem by using a simple trick. My aim was to paginate all posts under the same tags just like you guys can see in StackOverflow.
The modified controller function is
public function showTags($id)
{
$tag = Tag::find($id);
// when lazy loading
$tag->load(['posts' => function ($q) {
$q->orderBy('id', 'desc')->paginate(10);
}]);
return view('blog.showtags')->withTag($tag);
}
As you guys see that I move the paginate() function from find to load function which I use before for sorting post by descending order.
Now in view instead of using traditional method {!! $tag->links() !!} for making link of pagination
I use {!! $tag->paginate(10) !!}
With this line $tag = Tag::find($id)->paginate(5); You should get only one tag(or null if tag with your id dose not exist), and after that you want paginate it. If you want paginate your tags get all tags and after that paginate it Tag::paginate(5)