Laravel withtrashed in a relationship - php

I have an Order model and a Service model.
An order can be deleted (soft delete).
I want to list all orders, deleted and active and the service that it belongs to.
Order Model:
class Order extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
public function service ()
{
return $this->belongsTo('Service');
}
}
Service Model:
class Service extends Model
{
public function order()
{
return $this->belongsToMany('Order');
}
}
What I tried:
$company=Company::with('orders.service'=>function ($query) {
$query->withTrashed();
},'services'])->where('id',$company->id)->get();
But this returns no orders (and right now I only have 1 deleted order in my db)
Any ideas?
Thanks!!

you can use
public function order() {
return $this->belongsToMany('Order')->withTrashed();
}

First of all, a belongsToMany relationship always goes with another belongsToMany relationship at the other side, so you are not doing right the relationships.
If you want a many to many relationship, both models should have a belongsToMany relationship to the other model, and you must have a pivot table.
If you want a one to many relationship, one model should have a belongsTo relationship and the other a hasMany relationship.

Related

join three table relation by laravel eloquent model

I have three table which is explained below
User
id
email
password
specialities
id
name
active
results
id
specialitie_id
user_id
result
color
i am trying to relate results with the rest of the 2 tables, but i don't know how to do it, below is my model relation, please correct me if there's any issue, i can't fetch the data due to having wrong relation
Result Model
class Result extends Model
{
use HasFactory;
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
public function speciality()
{
return $this->belongsTo(Speciality::class);
}
}
User Model
class User extends Authenticatable implements MustVerifyEmail
{
public function result()
{
return $this->hasMany(Result::class);
}
}
i am trying to expect a correct result of my relation database tables in laravel
Since the results table is Intermediate Table Columns.use laravel belongsToMany method so no need to create results model.Treat results table as pivot table.
In User Model add relation like below
public function specialities()
{
return $this->belongsToMany(Speciality::class,'results')->withPivot('result','color');
}
Also read here Many To Many Relationships

How to load a nested relationship in Laravel

I have a model called CallbackRequest the model has a relationship with Loan model and that is the only relationship for CallbackRequest model.
CallbackModel:
public function loan() {
return $this->belongsTo(Loan::class);
}
Now Loan model itself has a relationship with a third model called Applicant.
Loan Model:
public function applicant() {
return $this->belongsTo(Applicant::class);
}
My point:
When I load CallbackRequest I eagerload loan model with it, all fine! But now I am wondering if there is a way to eagerload applicant model when I do:
Right now I access it like:
$modelResults = PublicCallback::with('loan')->get();
I get all callbacks with loan eagerloaded, but my point is I want when I eagerload loans in this case I want applicant to be loaded also !
Is there any way how to do this, is it possible ?
You can do this with:
$modelResults = PublicCallback::with(['loan', 'loan.applicant'])->get();
Ref: https://laravel.com/docs/5.5/eloquent-relationships#eager-loading
Just for posterity, there's also another way of loading nested relationships that can be done against a returned model, provided you have set up the relationships correctly:
Posts model:
public function comments() {
return $this->hasMany('App\Comment', 'quote_id', 'id');
}
Comments model:
public function user() {
return $this->belongsTo('App\User');
}
Then you can actually infer the user via relationship to a comment by drawing the post but loading an array of relations, eg:
$post = \App\Post::find($post_id);
return $post->load(['comments','comments.user']);

Eloquent belongsTo relationships

Not sure why it's now working for me.
I have two tables
events
- id
selections
- id
- event_id
From my Event model I want to relationship selections
class Event extends Model
{
...
public function selections()
{
return $this->belongsTo(Selection::class, 'event_id', 'id');
}
}
My problem is that $event->selections relationship is not working. Keep getting null back.
With the database schema, it is hasMany relation instead.
public function selections()
{
return $this->hasMany(Selection::class, 'event_id', 'id');
}
See One to many relationship in documentation.

How to return one property of a belongsTo model with the child model in Laravel resource controller

I'm using Laravel as a REST API for a SPA. I have a relationship where families have multiple contributions. The contributions table has a foreign key reference to family's id. I can call on the contributions route with the hasMany/belongsTo set up, and every contribution gets the entire family model it belongs to. But I don't need all that data, I just need a single field from the family table (not the id, but a different field) with each contribution.
Here are my models and resource controller:
class Family extends Eloquent {
protected $table = 'families';
// relationships
public function contributions() {
return $this->hasMany('Contribution');
}
}
class Contribution extends Eloquent {
protected $table = 'contributions';
// relationships
public function family() {
return $this->belongsTo('Family');
}
public function other_field() {
return $this->belongsTo('Family')->select('other_field');
}
}
class ContributionController extends BaseController {
public function index()
{
// works - but returns the entire family with every contribution
$contributions = Contribution::with('family')->get();
// returns other_field == null with every contribution
$contributions = Contribution::with('other_field')->get();
return Response::json($contributions->toArray(),
200);
}
Where am I going wrong with selecting this single field from the belongsTo relationship?
You can use query constraints on the relationship if you use eager loading.
Family::with(['contributions', function($query)
{
$query->select('column');
}])->get();

How do I get the `pivot table` model to trigger the save/saved model events when attach or detach are called in Laravel?

In Laravel 4 how do I get the pivot table model to trigger the save/saved model events when attach or detach are called?
It seems that the pivot table 'TeamUser' below is not actually needed for the attach/detach methods to work, so at a guess I believe that the model representing the pivot table is never invoked. And so the events are never triggered.
To ask another way:
When I call User::with('Team')->find(1)->teams()->attach(1); how to get TeamUser to trigger it's own events. Note that the above attach works perfectly fine, all the records are updated in the database.
User
class User extends Eloquent
{
// Relationship
public function teams()
{
return $this->belongsToMany('Team');
}
}
Team
class Team extends Eloquent
{
// Relationship
public function users()
{
return $this->belongsToMany('User');
}
}
Team User - The model for the TeamUser table/pivot table
class TeamUser extends Eloquent
{
public function save(array $options = array())
{
// do cool stuff when relationship is saved via
// attach/detach
}
}
You can add a $touches to the Team model.
class Team extends Eloquent
{
protected $touches = array('TeamUser');
// Relationship
public function users()
{
return $this->belongsToMany('User');
}
}
This will update the TeamUser updated_at field. I think this will also hit the save() method in the TeamUser model.
If that doesn't work, you can fire your own event in the Team save() method and listen to this event somewhere.
Event::fire('team.updated', array($team));
With the new version of Laraval 5.8, Pivot tables trigger the boot events. Check the release notes: https://laravel.com/docs/5.8/releases#pivot

Categories