Need help getting the right query on repository laravel 4.2 - php

I need to fetch the categorie name from the images to the ImagesRepository
So far in ImagesRepository i got:
public function latest($limit = 8)
{
return $this->image->whereNotNull('poster')
->orderBy('id', 'desc')
->limit($limit)
->get();
}
I tried using leftJoin but it didnt work:
public function latest($limit = 8)
{
return $this->image->whereNotNull('poster')
->orderBy('id', 'desc')
->limit($limit)
->leftJoin('category', 'id', '=', 'category_id')
->get();
}
Now i need to get the id from the Category Table that matches the category_id so i can get the right url link to the post.
Cause my result right now is :
localhost/test/1/name-1
and i need to get:
localhost/test/1-flowers/name-1
OK so after carefully looking at laravel documentation i figured it out the solution since they are already relationships in the eloquent all i have to do is call the table by simple adding a line...
public function latest($limit = 8)
{
return $this->image->whereNotNull('poster')
->with('category')
->orderBy('id', 'desc')
->limit($limit)
->get();
}

Related

Laravel Collection Query, Where I am going wrong?

My tables looks like this
area_trip
|id|dispatch_id|trip_id|status|
equipment_trip
|equipment_id|trips_id|dispatch_id|
trips
|id|dispatch_id|status
I am trying to pass collection to my resource. Can someone check my query and tell me what I am doing wrong as following query returning all the data matches dispatch_id whether it matches equipment_id or not. Btw I am new to laravel.
return
Resources::collection(
area_trip::where('dispatch_id', $request->dispatch_id)
->where('status', 1)
->orWhere('status', 9)
->whereHas('equipment_trip', function($query) use ($request) {
$query->where('equipment_trip.equipment_id', '=', $request->equipment_id);
})
->with(['equipment_trip', 'createdBy', 'updatedBy', 'area', 'trips'])
->orderBy('tripStartDate', 'ASC')
->orderBy('status', 'ASC')
->get());
Here is the relationship set up in area_trip model
public function equipment_trip()
{
return $this->belongsTo(equipment_trip::class, 'trip_id', 'trips_id');
}
I believe your whereHas sub query is incorrect also instead of where and orWhere use where in and you can define all statuses necessary, try this:
Resource::collection(area_trip::where('dispatch_id', $request>dispatch_id)
->whereIn('status', [1, 9])
->whereHas('equipment_trip', function($query) use ($request) {
return $query->where('equipment_id', '=', $request->equipment_id);
})
->with(['equipment_trip', 'createdBy', 'updatedBy', 'area', 'trips'])
->orderBy('tripStartDate', 'ASC')
->orderBy('status', 'ASC')
->get());

Want to call data from an array

public function showJobCategoryContent($id)
{
$jobsInfo= Job::where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);
return $jobsInfo->company_name;
}
public function showJobCategoryContent($id)
{
$jobsInfo= Job::where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);
return $jobsInfo['company_name'];
}
If i do that it shows --Undefined property also if i use return $jobsInfo['company_name'] now it shows blank page I know there is company_name index also i tried another index also. Why is it doing that?
Your main problem is not understanding what is returned by a paginate query. Have a good read of the docs for this https://laravel.com/docs/5.5/pagination#paginating-query-builder-results
That being said there are better ways of doing this with Laravel.
return Job::where('category_id', '=', $id)->select('company_name')->where('published', '=', 1)->get();
Will return a Collection of just company_name using the select function in the query builder.
https://laravel.com/docs/5.5/queries#selects

Laravel Eloquent non-lambda parameters

I'm trying to retrieve a number of results from database using eloquent.
I dont have problem with that.
Example code
$flights = App\Flight::where('active', 1)
->orderBy('name', 'desc')
->take(10)
->get();
Now lets suppose I have a variable that if it's true i want to add one more WHERE clause. For example if $domestic == true then i want something like this:
$flights = App\Flight::where('active', 1)
->where('domestic',1)
->orderBy('name', 'desc')
->take(10)
->get();
So I dont like to do, because it's not nice.
if($domestic) {
$flights = App\Flight::where('active', 1)
->where('domestic',1)
->orderBy('name', 'desc')
->take(10)
->get();
} else {
$flights = App\Flight::where('active', 1)
->orderBy('name', 'desc')
->take(10)
->get();
}
Ideally i want to pass only the where clause eg.
if(#domestic) { $flights->where('domestic',1) }
But this is not working.
What is the best way to pass additional where clauses whenever needed?
$flights = App\Flight::where('active', 1)
->orderBy('name', 'desc')
->when($domestic, function ($query){
return $query->where('domestic',1)
})
->take(10)
->get();
The laravel query builder has some real gems like the when clause, the when clause will only execute the closure if the first parameter is true (in this case $domestic)
This specific function can be found here. On the same way more of these functions can be found.
Solution is:
$flights = App\Flight::where('active', 1);
if($domestic) {
$flights->where('domestic',1);
}
$results = $flights->orderBy('name', 'desc')
->take(10)
->get();
Use Query Scopes
Write them on your model, quick example on flight model:
public function scopeIsDomestic($query,$domestic){
if($domestic == 1){
return $query->where('domestic',1);
}else{
return $query; //you can return the inverse if you need it -> where domestic <> 1
}
}
And now use it like this
$flights = App\Flight::where('active', 1)
->isDomestic(1)
->orderBy('name', 'desc')
->take(10)
->get();
It provides a nice way to keep the code maintainable since you can update the scope on all your queries at the same time by modifying it on a single place

cant get the data I want from two different tables using Laravel

I have a table called instructor_class: user_id, class_id and I have another table classes: id, time, active.
I would like to show classes for a single user but only those classes that active is 0 or 1.
My current code looks like this:
return InstructorClass::with('classes.session')->where('user_id', '=', $userId)->get();
This code is displaying me everything, then I tried the following code:
$active = 1;
return InstructorClass::with(['classes' => function ($q) use ($active) {
$q->where('active', '=', $active); // '=' is optional
}])
->where('user_id', '=', $userId)
->get();
This again returns me same records, but of course the class property is null for each record, which at some point looks correct, but my point is if the 'active' field does not corresponds at the classes table do not show the record, seems like the where() stm within with() is optional..
I am kinda stuck here...
Would appreciate your help, opinions!
You can use ::has('classes') to only return the models that have related classes
return InstructorClass::has('classes')->with(['classes' => function ($q) use ($active) {
$q->where('active', $active);
}])
->where('user_id', '=', $userId)
->get();
Never thought it could be this simple:
return InstructorClass::with('classes.session')
->join('classes', 'classes.id', '=', 'instructor_class.class_id')
->where('classes.active', '=', 1)
->where('user_id', '=', $userId)
->get();

Laravel: Sort Table Joined Using 'With' Clause

I'm using Laravel 4 and Eloquent ORM. I'm currently pulling records from my database using the following code:
public function index($type, $id)
{
$asset = Asset::where('public_id', '=', $id)
->with('attachments')
->with('attachments.attachment')
->with('tracks')
->with('tracks.track')
->where('locale', '=', Config::get('app.locale'))
->first();
return View::make('view-asset.index')
->with('asset', $asset)
->with('type', $type);
}
The table joined to this query using the with('tracks') statement has a column in it called track_order - I would like to be able to sort the rows returned by this part of the query by that column so that the tracks stored in the database are returned in the correct order.
Is it possible to do this and if so, how should I do it? So far I've tried something like this:
public function index($type, $id)
{
$asset = Asset::where('public_id', '=', $id)
->with('attachments')
->with('attachments.attachment')
->with('tracks')
->with('tracks.track')
->where('locale', '=', Config::get('app.locale'))
->orderBy('tracks.track_order', 'ASC')
->first();
return View::make('view-asset.index')
->with('asset', $asset)
->with('type', $type);
}
Which doesn't work and I can't figure out a way of doing this other than splitting things up into multiple queries.
You most certainly can:
with(['tracks' => function($query)
{
$query->orderBy('track_order', 'asc');
}])
Refer to Eager Loading Contraints in the documentation for more.

Categories