Every time I try to setup my pagination:
Missing argument 1 for Illuminate\Support\Collection::get()
My controller:
public function index()
{
$products = DB::table('products')
->where('product_group_id', '=', 1)
->paginate(15)
->get();
return view('product.index', [
'products' => $products,
]);
}
My view:
{{ $products->links() }}
What goes wrong here?
You don't need ->get() here. ->paginate() gets your records from the database and returns a collection of those 15 items.
When you're running ->get() here you're attempting to run it on the collection that is returned which expects a $key and is used to get a specific item out of a collection.
You should do this:
$products = DB::table('products')
->where('product_group_id', '=', 1)
->paginate(15);
return view('product.index', [
'products' => $products,
]);
or with Eloquent
$product = Product::where('product_group_id', '=', 1)
->paginate(15);
return view('product.index', [
'products' => $products,
]);
Note: I have put the filters before the paginate() call to ensure that the where clause is part of the database query rather than trying to filter the resulting collection/paginator
When you call the paginate() method on a Illuminate\Database\Query\Builder object, You will get an instance of \Illuminate\Pagination\LengthAwarePaginator. That itself does not have a get()-Method, but the Illuminate\Pagination\AbstractPaginator it extends has a magic __call() function which forwards the call to the underlying Collection.
Now, Illuminate\Support\Collection does have a get() method, but it takes the key of the element you want to get out of the Collection as an argument, hence the error you get.
Now, I suppose what you actually want to achieve standard pagination with links for page numbers and "forward" and "back" buttons. If so, you should just stick to the documentation: Get the data just the way you did, just leave out the get(), then display it in a view the way its shown here.
EDIT: Just read about the Method links does not exist error you get. That is indeed strange. Builder::paginate() definitely returns an Instance of LengthAwarePaginator which itself definitely has a links() method.
Is there perhaps some more code that is relevant to this problem which you havent shown us yet? Maybe in your view?
Related
Before I was simply doing a query that selects some field and some conditions. This line of code is giving me the correct result.
public function index()
{
// Get links
$links = Link::select('id', 'url', 'short_url', 'counter', 'expired_on')
->orderBy('id', 'desc')
->where('delete_flg', 0)
->get();
// Return data
return view('dashboard')->with(
array(
'links' => json_decode($links),
'current_datetime' => Carbon::now()
)
);
}
Now I want to implement pagination to the above line.
$links = Link::select('id', 'url', 'short_url', 'counter', 'expired_on')
->orderBy('id', 'desc')
->where('delete_flg', 0)
->get()->paginate(2);
When I try using paginate(2) at the end I get error:
Method Illuminate\Database\Eloquent\Collection::paginate does not exist.
So from some other tutorial I tried without ->get() and then paginate
Then I get such error.
count(): Parameter must be an array or an object that implements Countable
I am confused on how to implement paginate.
Can anybody please help me?
You can simply do following:
$links = Link::select('id', 'url', 'short_url', 'counter', 'expired_on')
->orderBy('id', 'desc')
->where('delete_flg', 0)
->paginate(2);
paginate already acts like a ->get()
And this is how you return the data / collection to your view:
// return data
return view('dashboard', compact('links'));
Alternative to compact:
return view('dashboard')->with([
'links' => $links
]);
Then in your view you can do whatever you wish to do with the data:
#foreach($links as $link)
<p>{{ link }}</p>
#endforeach
This is a documented change in PHP 7.2. You need to either update Laravel to 5.6+ or downgrade PHP to version 7.1.
Furthermore you have to use paginate() without ->get(), you should also take a look at the pagination documentation.
How do I get a row that was sofdeleted for example
This is my code:
$mov = $emp->movimientos()->where('movimiento.linea_id', intval($request->id_caso))->with('producto_nombre', 'costo_promedio');
I have this consult, one movimientos is related with a costo_promedio, but if in some case acosto_promedio is softdeleted the result in my consult $mov will give me null in the part of costo_promedio.
The thing is, where do I have to puth the withTrashed() method to get all data even the ones that were softdeleted
Thx for the help
Use with() with a closure:
$mov = $emp->movimientos()
->where('movimiento.linea_id', intval($request->id_caso))
->with([
'producto_nombre',
'costo_promedio' => function($query) {
$query->withTrashed();
}
]);
you can call withTrashed() function anywhere in 'Eloquent Query Builder' instance, but before get() or first() finction.
to eager load relationship with trashed, you can give a closure to the relationship.
$mov = $emp->movimientos()->where('movimiento.linea_id', intval($request->id_caso))
->with([
'producto_nombre',
'costo_promedio' => function($q) {
$q->withTrashed();
}
])->get();
I have a table called List which i planned to be displayed into view with this command : $lists= List::with('user', 'product.photodb', 'tagCloud.tagDetail')->get();. But, i want the data displayed is only those that has TagID equal to the one user inputted. Those data can be retrieved from TagCloud table.
What i am currently doing is :
$clouds = TagCloud::select('contentID')
->where('tagDetailID', '=', $tagID)
->get();
$lists = List::with('user', 'product.photodb', 'tagCloud.tagDetail')
->where('id', '=', $clouds->contentID)
->get();
But when i tried to run it, it only return a null value, even though when i am doing return $clouds, it does returned the desired ID.
Where did i do wrong ? Any help is appreciated !
A couple of gotchas with your current solution.
Using get() returns an Illuminate\Database\Eloquent\Collection object. Hence you can't use $clouds->contentID directly since $clouds is a collection (or array if you prefer). See Collection Documentation.
where(...) expects the third parameter to be a string or integer, aka single value. Instead, you are passing a collection, which won't work.
The correct way is to use whereHas() which allows you to filter through an eager loaded relationship.
Final Code:
$lists = List::with('user', 'product.photodb', 'tagCloud.tagDetail')
->whereHas('tagCloud',function($query) use ($tagID) {
return $query->where('contentID','=',$tagID);
})
->get();
See WhereHas Documentation.
What you want is whereHas()
$list = List::with(...)
->whereHas('relation', function($q) use($id) {
return $q->where('id', $id);
})->get();
Apply Where condition in you tagCloud model method tagDetail
public function tagDetail(){
return $q->where('id', $id);
}
This is my Laravel controller code
public function switchInfo($prisw, $secsw){
$cur_sw_pair_id = DB::table('sw_pairs')
->select('sw_pair_id')
->where('pri_sw','=',$prisw)
->where('sec_sw','=',$secsw)
->get();
$infolist = DB::table('cust_sw_pair')
->select('interface','pri_sw_vlan','sec_sw_vlan','pri_sw_admin_status','sec_sw_admin_status','description')
->where('sw_pair_id', '=', $cur_sw_pair_id)
->get();
return view('switchinfo.switchinfoview',compact('infolist'));
}
when this code executing it gives Object of class stdClass could not be converted to string error. How can i solve this? How can i pass my infolist into switchinfoview view without getting this error?
You can use pluck() to get value of a column.
Your first query should like this:
$cur_sw_pair_id = DB::table('sw_pairs')
->where('pri_sw','=',$prisw)
->where('sec_sw','=',$secsw)
->pluck('sw_pairs');
Keep the second query as it is.
Hope it will help.
The issue is that ->get() returns a collection, which is a 0-indexed collection of results (rows) from the database. In your case, you want to be using the following query:
$cur_sw_pair_id = DB::table('sw_pairs')
->select('sw_pair_id')
->where('pri_sw','=',$prisw)
->where('sec_sw','=',$secsw)
->first();
And then accessing the property sw_pair_id of $cur_sw_pair_id, like so:
$infolist = DB::table('cust_sw_pair')
->select('interface','pri_sw_vlan','sec_sw_vlan','pri_sw_admin_status','sec_sw_admin_status','description')
->where('sw_pair_id', '=', $cur_sw_pair_id->sw_pair_id)
->first();
Then, in your view, you can access all the properties (anything in the ->select() statement) of $infolist using $infolist->PROPERTY_HERE
Note that using ->first() is essentially using the same as ->get();, but you have to access the results of ->get() using an index, so
$cur_sw_pair_id[0]->sw_pair_id
Hope that provides some insight for you.
I'm trying to return a number of recent posts from my database, ordered by date, and I then want to select and return the month the post was made in via my model's getMonthAttribute() accessor method. To accomplish this, I'm using scoped queries. This all works fine when I use first() to return just a single result, but when I use take(1) or take() with any valid numerical input, I receive the following error:
Undefined property: Illuminate\Database\Eloquent\Collection::$month
In my model, I have this month attribute accessor:
public function getMonthAttribute() {
return Carbon::createFromFormat('Y-m-d',$this->date)->format('F');
}
and my scoped query to return a variable number of recent posts (the portion of my code that is not working):
public function scopeRecent($query, $take = 1) {
// Replace take with first and I no longer receive the above error.
return $query->where('status', '=', '1')->orderBy('date', 'DESC')->get()->take($take);
}
Here is how I'm accessing my data in the view:
{{ $post->recent()->month }}
Any suggestions?
This is because ->first() returns an eloquent model. Using the get() method returns an eloquent collection (an array of eloquent models) instead. So you must run a foreach over the collection like so:
#foreach($post->recent() as $recent)
{{$recent->month }}
#endforeach