John Davidson

php - Laravel get all from with belongTo value

0 comments
Message:


In my Laravel 8 project I have two tables A and B:


| A     |
---------
| ID |
| B_ID |
| VALUE |


| B |
-----------
| ID |
| VALUE |
| Private |

In my models I have:


A{
public function b()
{
return $this->belongsTo(B::class);
}
}

B{
public function as()
{
return $this->hasMany(A::class);
}
}

In my controller I have:


public function index()
{
$a = A::join('bs', 'as.b_id', '=', 'b.id')->get(['as.value', 'bs.value']);

return $a;
}

Is'nt there a more elegant Laravel way to do this?
I would like to get all records from table A with the value from table B but without the private value from B. (There could be a lot of entries in Table A, Table B only has some values (<20) ).



My Answer:
Yes, there is a more elegant way to achieve this in Laravel using Eloquent relationships. You can define a relationship in your A model to directly access the related B model's value without having to manually join the tables in your controller.

In your A model, you can define a relationship like this:

php
public function b()
{
return $this->belongsTo(B::class, 'b_id');
}


Then in your controller, you can simply eager load the B relationship when querying for all records from table A:

php
public function index()
{
$a = A::with('b')->get();

// Filter out the private values from B
$a = $a->filter(function ($item) {
return $item->b->private !== 'private_value';
});

return $a;
}


This way, you can access the related B model's value directly as `$item->b->value` in your view or wherever you need it. This approach is more in line with Laravel's Eloquent ORM and makes your code more readable and maintainable.

Rate this post

5 of 5 based on 7577 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us