Laravel orderBy does not exist - laravel

I'm doing the simple query
$offers = Offer::join('offer_speciality', 'offers.id', 'offer_speciality.offer_id')
->join('specialities', 'offer_speciality.speciality_id', 'specialities.id')
->when($speciality, function($query, $speciality) {
return $query->where('specialities.number', $speciality)->get();
})
->orderBy('created_at','desc')->paginate(9);
and then error:
Method Illuminate\Database\Eloquent\Collection::orderBy does not
exist
I'm not sure what is it?

At the point of running ->get() a collection is being returned and ->orderBy() is not a function you can run on a collection with all the functions available being listed in the documention.
You've got your ->get() before your ->orderBy() and that wont work. Plus you don't need ->get() as you've got ->paginate(9)
You need:
$offers = Offer::join('offer_speciality', 'offers.id', 'offer_speciality.offer_id')
->join('specialities', 'offer_speciality.speciality_id', '=', 'specialities.id')
->when($speciality, function($query, $speciality) {
return $query->where('specialities.number', $speciality)
})
->orderBy('created_at','desc')->paginate(9)

Related

laravel does not exist on this collection instance

$orders = Orders::select('orders.id as order_id', 'collection_color.color_name as color', 'collection_color.id as collection_color_id', DB::raw('SUM(order_piece.piece) As piece'))
->join('order_piece', 'order_piece.order_id', '=', 'orders.id')
->join('collection_color_size_barcode', 'collection_color_size_barcode.id', '=', 'order_piece.collection_color_size_barcode_id')
->join('collection_color', 'collection_color.id', '=', 'collection_color_size_barcode.collection_color_id')
->whereIn('orders.id', $request->order_id)
->groupBy('order_piece.order_id')
->orderBY('orders.delivery_date', 'ASC')
->get();
return $orders; => [{"order_id":30,"color":"Kahverengi","collection_color_id":21,"piece":"500"}]
return $ccfc = CollectionColorFabricColor::whereIn('collection_color_id', $orders->collection_color_id)->get();
Property [collection_color_id] does not exist on this collection instance. i am getting error can you help me
The error is most likely due to this in your second code snippet: $orders->collection_color_id. $orders is a collection, so the property doesn't exist in that object. What you actually need is to pluck those values from that collection like so:
return $ccfc = CollectionColorFabricColor::query()
->whereIn('collection_color_id', $orders->pluck('collection_color_id'))
->get();
Because your $orders is collection, you need to get collection_color_id array like this :
$arrayColors = $orders->pluck('collection_color_id')->toArray();
then
return $ccfc = CollectionColorFabricColor::whereIn('collection_color_id', $arrayColors)->get();

Laravel Query Builder Method addSelect does not exist

I tried to pass data from the database to view. Now I have to write some SQL code in the controller. Is it possible to do more queries from two Query Builder instances? Like my code, obviously, it didn't work; it throws an error.
Method Illuminate\Support\Collection::addselect does not exist.
Has anyone a better idea?
class StatisticsController extends Controller
{
public function statistic()
{
$right = DB::table('answers')
->select('questions.question_title', 'questions.chapters_id',
DB::raw('count(*) as rightanswers'))
->join('questions', 'questions.id', '=', 'answers.questions_id')
->where('answers.is_correct', 1)
->groupBy('questions.question_title', 'questions.chapters_id')
->get();
$wrong = DB::table('answers')
->select('questions.question_title', 'questions.chapters_id',
DB::raw('count(*) as wronganswers'))
->join('questions', 'questions.id', '=', 'answers.questions_id')
->where('answers.is_correct', 0)
->groupBy('questions.question_title', 'questions.chapters_id')
->get();
$data = $right->addselect('questions.title', 'chapters_id',
'rightanswers/(rightanswers+wronganswers) as rightigeRate')
->join('wrong', 'right.questions.title', '=', 'wrong.questions.title')
->get();
return view('/statistics', compact('data'));
}
}

Laravel: hasMany relationship breaks query with where clause

This is my first Laravel project, so maybe I'm misunderstanding something.
I have Clients and Campaigns contollers, and clients are setup with hasMany campaigns
class Client extends Model
{
public function campaigns(){
return $this->hasMany('App\Campaign');
}
}
in the Clients Show method, this query doesn't work:
$client = Client::find($id);
$campaigns = $client->campaigns
->where(function($query) use($startdate, $enddate) {
$query->wherebetween('start_date', [$startdate, $enddate])
->orwherebetween('end_date', [$startdate, $enddate]);
})
->sortBy('start_date')
->groupBy(function($val) {
return Carbon::parse($val->start_date)->format('F Y');
});
I get the error:
explode() expects parameter 2 to be string, object given
The error page shows a red line on the }) after the orwhereBetween clause.
But this query does work:
$campaigns = DB::table('campaigns')
->where('client_id', $client->id)
->where(function($query) use($startdate, $enddate) {
$query->wherebetween('start_date', [$startdate, $enddate])
->orwherebetween('end_date', [$startdate, $enddate]);
})
->orderBy('start_date')
->get()
->groupBy(function($val) {
return Carbon::parse($val->start_date)->format('F Y');
});
My problem is, the second query doens't let me access $campaign->tasks once I'm on the show view, which I need.
So, does anyone know why the where clause would cause an issue when accessing $client->campaigns but not when using DB?
That's because before you call get method the object is an instance of Eloquent Builder class and the groupBy method doesn't accepts any parameter as a closure. However after calling the get method it changes to an instance of Collection class which has groupBy method as well and it accepts closure.
By the way sortBy doen't belong to Eloquent builder instead you have to use orderBy before executing your query using get method.
Here are the available methods of Collection
https://laravel.com/docs/5.7/collections#available-methods
Try this code out and don't forget to call the methods camel case otherwise it can make you serious problems on deployment.
$dates = $client->campaigns()
->where(function($query) use($startdate, $enddate) {
$query->whereBetween('start_date', [$startdate, $enddate])
->orWhereBetween('end_date', [$startdate, $enddate]);
})
->orderBy('start_date')
->get()
->groupBy(function($val) {
return Carbon::parse($val->start_date)->format('F Y');
});
foreach($dates as $campaigns){
foreach($campaigns as $campaign){
dump($campaign->tasks);
}
}

How to use count in Query builder Laravel5.6

This is my query builder. But an error is shown
ERROR => count(): Parameter must be an array or an object that implements
Countable
Route::get('project', function () {
$project = DB::table('pams_project')
->join('pams_developer', 'pams_project.dev_id', '=', 'pams_developer.id')
->select(array('pams_developer.developer_name',DB::raw(count('pams_project'.'dev_id'))))
->get();
return view('projectByDeveloper', ['project' => $project]);
});
can anyone figure out my problems ?
use DB::raw("count(pams_project.dev_id) as count")
$project = DB::table('pams_project')
->join('pams_developer', 'pams_project.dev_id', '=', 'pams_developer.id')
->select(array('pams_developer.developer_name',DB::raw("count(pams_project.dev_id) as count")))
->get();
But also make sure to use GroupBy() with this.
If you want to get the count of collection u can simply use $project->count()
Hope this helps

Sort collection by relationship value

I want to sort a laravel collection by an attribute of an nested relationship.
So I query all projects (only where the project has tasks related to the current user), and then I want to sort the projects by deadline date of the task relationship.
Current code:
Project.php
public function tasks()
{
return $this->hasMany('App\Models\ProjectTask');
}
Task.php
public function project()
{
return $this->belongsTo('App\Models\Project');
}
UserController
$projects = Project->whereHas('tasks', function($query){
$query->where('user_id', Auth::user()->id);
})->get()->sortBy(function($project){
return $project->tasks()->orderby('deadline')->first();
});
I don't know if im even in the right direction?
Any advice is appreciated!
A nice clean way of doing this is with the . operator
$projects = Project::all()->load('tasks')->sortBy('tasks.deadline');
I think you need to use something like join() and then sort by whatever you need.
For exapmle:
Project::join('tasks', 'tasks.project_id', '=', 'projects.id')
->select('projects.*', DB::raw("MAX(tasks.deadline) as deadline_date"))
->groupBy('tasks.project_id')
->orderBy('deadline_date')
->get()
Update
Project::join('tasks', function ($join) {
$join->on('tasks.project_id', '=', 'projects.id')
->where('tasks.user_id', Auth::user()->id)
->whereNull('tasks.completed');
})
->select('projects.*', DB::raw("MAX(tasks.deadline) as deadline_date"))
->groupBy('tasks.project_id')
->orderBy('deadline_date')
->get()
Update2
Add with in your query as:
->with(['tasks' => function ($q) {
$q->where('user_id', Auth::user()->id)
->whereNull('completed');
})
Try This,
$tasks = Task::with('project')
->where('user_id',Auth::user()->id)
->orderBy('deadline')
->get();
After that you can access project properties like below
$tasks->first()->project()->xxx

Resources