Show all entries where relationship exists (eloquent) - laravel-5

Trying to build an eloquent query to return all results in the database where a relationship exists.
$deliveries = Deliverer::has('deliveries')->get()->toArray();
dd($deliverer);
This is returning results which include multiple deliverers without any deliveries.
Deliverer Model includes:
public function deliveries() {
return $this->hasMany(Deliveries::class)->latest();
}
Delivery Model includes:
public function deliverer() {
return $this->belongsTo(Deliverer::class);
}
Can anybody see what is going wrong here please?

Related

Check if an Eloquent element is related to another one (with MorphToMany relationship)

I have those tables :
- blocks
- bloackables
--reports
--modalities
--reportGroups
Block.php :
public function reports()
{
return $this->morphedByMany(Report::class, 'blockable');
}
public function modalities()
{
return $this->morphedByMany(Modality::class, 'blockable');
}
public function reportsGroups()
{
return $this->morphedByMany(ReportsGroup::class, 'blockable');
}
Report.php :
public function blocks()
{
return $this->morphToMany(Block::class, 'blockable');
}
The same type of relationship exists for ReportGroups and Modalities...
Basically I'd like to load a Block instance and then check if the instances of Report, Modality and ReportGroup are related to this block.
The idea is to create an edition form with a checkbox for every Report, Modality or ReportGroup instances).
What are the strategies ? I read the Eloquent documentation but I am still confused...
Best regards,
Take care...
Nicolas
i'm not sure i understand you completely:
you have
$reportInstances,$modalityInstances,$reportGroupInstances
and you want to determine who has relation to the current block;
ok, you should load the model 'block' with its relations, and check the relation existance:
$blcokWithRelations=Block::with(['reports','modalities','reportsGroups'])->find($block->id):
foreach($reportInstances as $reportInstance)
{
if($blcokWithRelations->reports->where('id','=',$reportInstance->id)->get->first()!=null)
// this report has relation to the current block
else
// this report doesn't have relation to the current block
}
the same goes for the rest of relations

Laravel Create multiple records in Pivot table

I'm trying to create a function in our Laravel 5.8 app that would add multiple records to a pivot table. At present we have the following setup;
Users
Training Courses
Users Training Courses (pivot table for the above relationships, with a few extra fields)
I want to be able to show all users in the database, then check their name, pick a training course and hit "Add" and it'll create a record in the pivot table for each user that was selected.
I can't figure out where to start with this - it seems like I need to have a "for each user selected, run the store function" loop in the controller, but I have no idea where to start.
I wasn't sure if there was an easy way to do this in eloquent or not. Is there a simple way to do this?
Eloquent does this automatically if you set up the relationships correctly and you don't have to worry about pivot tables.
class Users
{
public function trainingCourses()
{
return $this->hasMany(TrainingCourses::class);
}
}
class TrainingCourses
{
public function user()
{
return $this->belongsTo(User::class);
}
}
Then you can use the save() method to create the relationship. But I find it better to wrap this function inside a helper method that you can use throughout your code:
class Users
{
...
public function assignTrainingCourse(TrainingCourse $trainingCourse)
{
return $this->trainingCourses()->save($trainingCourse);
}
}
In your code, you could then do something as simple as this:
$user = User::find(1);
$trainingCourse = TrainingCourse::find(1);
$user->assignTrainingCourse($trainingCourse);
Building on this, suppose you have the following route to assign a training course, where it expects a trainingcourse_id in the request:
Route::post('/users/{user}/trainingcourses', 'UserTrainingCoursesController#store');
Thanks to route model binding, Laravel can inference the parent model (user) from the URL, and your controller might look like this:
// UserTrainingCoursesController.php
public function store(User $user)
{
$trainingCourse = TrainingCourse::find(request()->input('trainingcourse_id'));
$user->assignTrainingCourse($trainingCourse);
return back();
}
Of course, you'll want to put some validation in here, but this should get you started.

How to setup conditional relationship on Eloquent

I have this (simplified) table structure:
users
- id
- type (institutions or agents)
institutions_profile
- id
- user_id
- name
agents_profile
- id
- user_id
- name
And I need to create a profile relationship on the Users model, but the following doesn't work:
class User extends Model
{
public function profile()
{
if ($this->$type === 'agents')
return $this->hasOne('AgentProfile');
else
return $this->hasOne('InstitutionProfile');
}
}
How could I achieve something like that?
Lets take a different approach in solving your problem. First lets setup relationship for the various models respectively.
class User extends Model
{
public function agentProfile()
{
return $this->hasOne(AgentProfile::class);
}
public function institutionProfile()
{
return $this->hasOne(InstitutionProfile::class);
}
public function schoolProfile()
{
return $this->hasOne(SchoolProfile::class);
}
public function academyProfile()
{
return $this->hasOne(AcademyProfile::class);
}
// create scope to select the profile that you want
// you can even pass the type as a second argument to the
// scope if you want
public function scopeProfile($query)
{
return $query
->when($this->type === 'agents',function($q){
return $q->with('agentProfile');
})
->when($this->type === 'school',function($q){
return $q->with('schoolProfile');
})
->when($this->type === 'academy',function($q){
return $q->with('academyProfile');
},function($q){
return $q->with('institutionProfile');
});
}
}
Now you can access your profile like this
User::profile()->first();
This should give you the right profile. Hope it helps.
you can do this by use another method please check this:
a blog Post and Video model could share a polymorphic relation to a
Tag model. Using a many-to-many polymorphic relation allows you to
have a single list of unique tags that are shared across blog posts
and videos. First, let's examine the table structure:
https://laravel.com/docs/5.4/eloquent-relationships#many-to-many-polymorphic-relations
Looks like that should be $this->type rather than $this->$type - since type is a property, not a variable.

How do i access data using two BelongsTo?

I have three tables - "courses", "lessons" and "tasks". Each lesson belongsTo a course, and each task BelongsTo a lesson. I want to output a task, showing the task name, the lesson name, and the course name. How do I access the course table data? To get the lesson information linked to a course, I have used the following in my Task model:
$lessonName = $this->lessons->lesson_name;
To get the course name associated to that lesson, I have tried the following with no success, but I am really guessing here:
$courseName = $this->lessons->courses->course_name;
My model relationships are as follows:
Course.php
public function lessons()
{
return $this->hasMany('App\Lesson');
}
Lesson.php
public function tasks()
{
return $this->belongsTo('App\Task', 'task_id', 'id');
}
Task.php
public function lessons()
{
return $this->belongsTo('App\Lesson', 'lesson_id', 'id');
}
Where am I going wrong? Thanks
there is another way you can do this by using accessors.
on your Task model do the following:
public function getLessonAttribute(){
return Lesson::where('id', $this->attributes[*foreign_key_field*])->first();
}
Here you receive all the data regarding the lesson that the task belongs to, and can use them as any other attribute (field) of the model.
on your Lesson model get the course that it belongs to.
public function getCourseAttribute(){
return Course::where('id', $this->attributes[*course_foreign_key_field*])->first();
}
and then assuming that $task is your collection, you can access the lesson and the course like the following in blade:
$task->lesson->lesson_name and $task->lesson->course->course_name
In your lesson.php model doesn't exist relationship courses so there are your issue. Use answer what is told you #jeroenF
So you want the inverse of hasManyThrough?
The hasManyThrough feature of Laravel (see their site) facilitates connecting your Courses to Task directly, without having the intermediate connection in a separate relationship.
You are looking for the inverse?

Laravel - Eloquent Relationships (Query made; Not fetching value)

I am trying to get some database information, and I can see the query is being done, but I am unable to come up with content... I have the follows:
class Vendor extends Eloquent {
public function spider()
{
return $this->hasOne('Spider');
}
}
class Spider extends Eloquent {
public function report()
{
return $this->hasMany('Report');
}
}
So... now I am trying to use it as:
$vendor = Vendor::find(1);
$vendor->spider->report->id;
This is not giving me any result - the id is not being fetched. However, I can tell a correct query is being made to the database...
select * from `report` where `report`.`spider_id` = ?
Why is it not giving me anything? I have tried several ways such as... $vendor->spider->first()->report->first()->id... and so on... but all I get is errors.
Thank's.
Report is of type hasMany so a Collection will be retrieved. Process that Collection to find the instance you want.

Resources