Method orderBy does not exist in Laravel Eloquent? - php

I have a piece of code like this:
$products = Product::all()
if ($search_value) {
$products = $products->where('name', 'LIKE', "%$search_value%");
}
$products = $products->orderBy('created_at', 'desc')->skip(10)->take(10)->with('tags')->get();
I got the following error:
BadMethodCallException in Macroable.php line 81:
Method orderBy does not exist.
I guess orderBy need to follow Product:: directly, but I can't save $products = Product::, can I?
Any suggestions? Thanks.

You're trying to use orderBy() method on Eloquent collection. Try to use sortByDesc() instead.
Alternatively, you could change $products = Product::all(); to $products = new Product();. Then all your code will work as you expect.

just use the one line code it will work fine
$product= Product::orderBy('created_at','desc')->get();

use sortByDesc('id') or simple sortBy() inside use the variable through which you wanna sort like i add id

If you want to get the list of all data and grab it in descending order try this:
$post = Post::orderBy('id', 'DESC')->get();

You are first getting all() data and then trying to sort which is wrong. You have to fix this by removing
$products = Product::all()
and changing your code into something like this
if ($search_value) {
$products = Product::where('name', 'LIKE', "%$search_value%");
}
else {
$products = Product::orderBy('created_at', 'desc')->skip(10)->take(10)->with('tags')->get();
}
Hope you get idea to tweak your code.

Your query is wrong.
remove all from $products = Product::all() and then put get() at the end of your query.

$table_Data = DB::table('tbl_product')->orderBy('id','DESC');
You can use this...

Related

Splitting Paginated Blade

Below is my controller code
$category_ids = array();
foreach($categories as $category){
$category_ids[] = $category->id;
}
$paginated_products = Product::where('status',1)->whereIn('category_id',$category_ids)->latest()->paginate(30);
Below is my blade view code
$first_ten_products = array_slice($paginated_products,0,9);
But am getting the error below how can i fix it. Thanks
array_slice(): Argument #1 ($array) must be of type array, Illuminate\Pagination\LengthAwarePaginator given
Your error is saying that $paginated_products is not an Array, and array_slice requires an Array to function. You can use ->toArray() as suggested in the comments/your answer, but there are also Laravel Collection methods for this:
$paginatedProducts = Product::where('status', 1)
->whereIn('category_id', $categories->pluck('id'))
->latest()
->paginate(30);
$chunkedProducts = $paginatedProducts->getCollection()->chunk(10);
Some changes:
Use ->pluck('id') instead of foreach()
The pluck() Method returns a Collection of the speicified values, and is a short-hand for what your foreach($models as $model) { $array[] = $model->id } accomplishes.
Define $chunkedProducts from your Paginated Product Models
->paginate(30) returns an instance of a LengthAwarePaginator, which has a method getCollection(), which can then be chained to the chunk() method. chunk(10) will return a Collection with X elements. In your case:
$firstTenProducts = $chunkedProducts[0];
$secondTenProducts = $chunkedProducts[1];
$thirdTenProducts = $chunkedProducts[2];
It would probably make more sense to pass these to the Frontend and loop them, like:
#foreach($chunkedProducts as $chunkOfTen)
<!-- Do something with each group of 10 Products -->
#endforeach
But you can use the chunks however you see fit, and however works with your project.
If I have refactored my code as below and it worked
$first_ten_products = array_slice($paginated_products->toArray(),0,9);
dd($first_ten_products['data']);
I just added the data property as above in the dd method and it worked

In laravel, get an errror when show the product items

I want to get some view data using laravel. here is my code:
public function brandsview($cate_url, $brand_url)
{
$brands = Brands::where('url',$brand_url)->first();
$brand_id = $brands->id;
$products = Products::where('brand_id',$brand_id)
->where('status','!=','Hide')
->where('status','Show')
->get();
return view('lokalproductspage.brands')
->with('brands', $brands)
->with('products', $products);
}
I get the error trying to get property 'id' of non-object. Please help me.
Looks like $brands return nothing, are you checked it?
If return of $brands is not stable may be u should add some checks before use attributes like 'id'
Change first() to firstOrFail(), which will let you know if you actually found a record. Normally your error suggests there was no record found. It is a nice way to show a 404 if the user put a bad url in.
$brands = Brands::where('url',$brand_url)->firstOrFail();

BadMethodCallException Method Illuminate\Database\Eloquent\Collection::paginate does not exist

After adding Paginate function I'm getting this error
$sub_categories = SubCategory::where('id', $id)->first();
$products = Products::where('subcategory_id', $sub_categories->id)->get()->paginate(10);
$sub_categories = SubCategory::where('id', $id)->first(), this will only give you null or one record, not a collection, so you can not use ->paginate(10); chain it. You will only get one record at the most, why you need to paginate?
Update
so first for the sub_categories you do not need to paginate, as you just want one record. so the code should be like this.
$sub_categories = SubCategory::where('id', $id)->first();
second, if you want to paginate $products you should do this,
if ($sub_categories)
{
$products = Products::where('subcategory_id', $sub_categories->id)->paginate(10);
}

Access to multilevel relationships in laravel

can someone help me on getting data from multi level relationships in laravel?
I want to do something like
BagageAnnouncement->Announcement->user->profile->"name of the field"
$data = $request->text;
$filter = BagageAnnouncement::whereHas('announcement',function ($query) {
})->whereHas('user', function ($query) {
})->whereHas('profile',function($query){
$query->where('level',$data)
})->get();
Thank you guys for you answers I finally figure out a solution
$data = $request->text;
$filter = BagageAnnouncement::whereHas(
'announcement.user.profile',
function ($q2) use ($data) {
$q2->where('level',$data);
}
)->get();
Not sure what you want as the result, but if you want a single result, you can do like this:
$bagage = BagageAnnouncement::where(specify_your_condition)->first();
$filter = $bagage->user->profile->name_of_the_field;
If you want an array of results, change the first() to get() and make use of foreach
Of course, you will need to set up the relationships in your models first.

->where() is not working,any idea?

I have a problem. I had this code:
$model=VehicleModel::where('make_id','=',$make_id)->get();
return Response::json($model);
Its worked good,now I need to change something like that:
$maketable=$vehicletype.'_models';
$models=new VehicleModel;
$models->setTable($maketable);
$models->where('make_id',$make_id);
$model=$models->get();
return Response::json($model);
So,I added only just to set other table,and now the ->where is not working. Any idea?
Just use Query Builder:
$data = DB::table($maketable)->where('make_id', $make_id)->get();
Try this:
$data = DB::table($maketable)->whereMakeId($make_id)->get();

Categories