get the id from hasManyThrough relationship in laravel - php

I have 3 tables
Users table
Loan Amounts Table
Grant Loan amounts table
on my user model i used hasManyThrough relationship
public function loan_amounts()
{
return $this->hasManyThrough(
'App\LoanAmount',
'App\GrantLoanAmount',
'user_id',
'id',
'id',
'amount_id'
);
}
this relationship display the loan_amounts->amount in my user.show blade.
so if i just do {{$user}} it display the following:
{
"id":13,
"name":"antonitte",
"email":"antonitte!23#yahoo.com",
"email_verified_at":null,
"phone_number":"09472315875",
"verification_code":null,
"phone_verified_at":null,
"avatar":"user.jpg",
"created_at":"2019-09-23 18:50:57",
"updated_at":"2019-09-23 18:50:57",
"loan_amounts":[
{"id":1,"amount":"5000.00","default":1,"created_at":"2019-09-23 02:45:30","updated_at":"2019-09-23 02:45:30","laravel_through_key":13},
{"id":4,"amount":"20000.00","default":0,"created_at":"2019-09-23 02:46:37","updated_at":"2019-09-23 02:46:37","laravel_through_key":13},
{"id":2,"amount":"10000.00","default":0,"created_at":"2019-09-23 02:46:08","updated_at":"2019-09-23 02:46:08","laravel_through_key":13}
]
}
which is good. But my problem is I want to grab the id of grant_loan_amounts->id. so that I can send it to GrantLoanAmountsController#destroy for deletion
any suggestions? thanks!

Can try using the eloquent relationships which can be found in the laravel document querying-relationships (check on which laravel version you are using).
From your example you can try something like the following:
this should return a collection
$user->loan_amounts->pluck('id');
this should help to turn into an array
$user->loan_amounts->pluck('id')->toArray();

Related

Laravel Many-To-Many relation returns no results

I am currently learning Laravel and I have an issue which I can't seem to find a solution for. I have a many-to-many relation between two tables that always returns nothing. Let me show you the basic setup:
My posts Model:
// App\Post.php
protected $fillable = [
'name',
'description'
'videopath'
];
public function Tags()
{
return $this->belongsToMany('App\Tag');
}
public function Cats()
{
return $this->belongsToMany('App\Cat');
}
My tags model:
// App\Tag.php
protected $fillable = [
'name',
'description'
];
public function exercises()
{
return $this->belongsToMany('App\Exercise');
}
My posts controller:
// PostController.php
public function show($id)
{
$post = Post::find($id);
return view('posts', ['post'=>$post];
}
The view:
// posts.blade.php
#foreach($post->tags() as $tag)
//do stuff
#endforeach
The intermediate table is called post_tag and contains the post_id and tag_id columns. At first it returned the results as expected but after some while all of my posts didn't return any tags anymore. The cats model looks similar to the tags model. Anyone has an idea?
Check the name of your Tags function. In your view you are calling "tags" instead of "Tags".
Have you created the intermediate table in your database? If so, check the naming convention (alphabetic order) that Laravel uses to find it: in your case it should be tag_post. if not, customize the name of the table when defining the relationship.
Many To Many
Many-to-many relations are slightly more complicated than hasOne and hasMany relationships. An example of such a
relationship is a user with many roles, where the roles are also
shared by other users. For example, many users may have the role of
"Admin". To define this relationship, three database tables are
needed: users, roles, and role_user. The role_user table is derived from the alphabetical order of the related model names, and contains the user_id and role_id columns.
Taking your view:
#foreach($post->tags() as $tag)
//do stuff
#endforeach
$post->tags() will return the relationship instead of the actual collection. You want $post->tags instead or $post->tags()->get().

Laravel get model with relation's pivot condition

I need to get all appeals, that have appeal_stage.expiration_date less than NOW().
Now I have following solution:
public function scopeExpired($query) {
$query->join('appeal_stage', 'appeals.id', 'appeal_stage.appeal_id')
->where('appeal_stage.expiration_date', '<=', new Expression('NOW()'));
}
but resulted model dump shows that joined table is recognized as pivot table:
So, I want to ask - Is there some more convenient way to perform this request?
My suggestions is use Illuminate\Database\Eloquent\Relations\Pivot somehow, bu I do not quiet understand, how Pivot can be used here.
UPD 1
Models has next relations:
public function stages()
{
return $this->belongsToMany(Stage::class)->withPivot('prolongated_count', 'expiration_date')->withTimestamps();
}
public function appeals() {
return $this->belongsToMany(Appeal::class);
}
You should be able to do something like this:
$appeal->stages()->wherePivot('expiration_date', '<', $now)->get()
You should create relationship in appeal model
public function stages()
{
return $this->belongsToMany(Stage::class,'appeal_stage','appeal_id','stage_id')->wherePivot('expiration_date','<',Carbon::now())->withTimestamps();
}
In belongs To Many relationship second argument is your Pivot table name

Laravel relationship with pivot table

I have 3 tables in my database :
users (id);
interests (id);
users_interests (user_id, interests_id);
I want to be able to fetch all the user's interests in this way :
$interests = $user->interests
This is what I wrote in the User.php model, following laravel's doc:
public function interests() {
return $this->hasManyThrough(
'App\Interest', 'App\UserInterest',
'user_id', 'id', 'interest_id'
);
}
but it returns empty even though the user has a game. So there has to be something I'm doing wrong
Anyone to help me ?
I think a belongs to many would do the job:
public function interests() {
return $this->belongsToMany(
'App\Interest',
'users_interests',
'user_id',
'interests_id'
);
}
Quite similar to the example in the docs
If you were to rename users_interests table to interest_user and the column
interests_id to the singular form you would just need the first parameter:
public function interests() {
return $this->belongsToMany(App\Interest::class);
}
From my understanding the hasManyThrough is used to jump forward within a relation (also described in the docs):
The "has-many-through" relationship provides a convenient shortcut for
accessing distant relations via an intermediate relation.

Laravel Pivot Tables - accessing from inverse relation-table

UPDATE: Apparently $problem->userRatings()->count(); returns 1, so a record does exist, but the script still doesn't enter the foreach loop for some reason...
UPDATE 2/Solution: I feel incredibly foolish, but the reason it isn't working, is that I was calling foreach($problem->userRatings() as $rating){ when it should be foreach($problem->userRatings as $rating){ (dynamic property)
In my database I have problem_ratings, problems, and users. I have models for users and problems, and problems_ratings is a pivot table between problems and users with an extra 'content' column that stores the numeric rating value (1-5).
The many-to-many relation in my Problem model:
public function userRatings(){
return $this->belongsToMany('User', 'problem_ratings', 'author_id', 'problem_id')->withPivot('content');
}
The many-to-many relation in my User model:
public function problemRatings(){
return $this->belongsToMany('Problem', 'problem_ratings', 'author_id', 'problem_id')->withPivot('content');
}
When creating a problem_ratings element, I attach it to my user model like so:
$user->problemRatings()->attach($problem->id, array('content' => $val));
I can access the pivot table through the user, but when I try this:
foreach($problem->userRatings() as $rating){
echo "In average loop";
$newAverage = ($rating->pivot->content) + $newAverage;
}
it doesn't find any records, even though some exist in the database. Am I using these relations correctly?
Thanks in advance!
In the Problem model I think your relationship should looks something like :
public function userRatings(){
return $this->belongsToMany('User', 'problem_ratings', 'problem_id', 'author_id')->withPivot('content');
}
When using a foreach loop over something like this, you need to use dynamic properties (ie. without parentheses):
foreach($problem->userRatings as $rating){ instead of foreach($problem->userRatings() as $rating){

getting the value of an extra pivot table column laravel

I have a phone_models, phone_problems, and a phone_model_phone_problem pivot table. The pivot table has an extra column 'price'.
PhoneModel:
class PhoneModel extends \Eloquent
{
public function problems()
{
return $this->belongsToMany('RL\Phones\Entities\PhoneProblem')->withPivot('price');
}
}
PhoneProblem:
class PhoneProblem extends \Eloquent
{
public function models()
{
return $this->belongsToMany('PhoneModel')->withPivot('price');
}
}
What I'm trying to do is get the price of a specific phone with a specific problem.
This is how I have it now but I feel like Laravel has a built in Eloquent feature I can't find to do this in a much simpler way:
$model = $this->phoneService->getModelFromSlug($model_slug);
$problem = $this->phoneService->getProblemFromSlug($problem_slug);
all this does is select the specific model and problem from their slug.
then what I do is with those credentials I get the price like so:
$row = DB::table('phone_model_phone_problem')
->where('phone_model_id', '=', $model->id)
->where('phone_problem', '=', $problem->id)
->first();
so now I can get the price like so $row->price but I feel like there needs to be a much easier and more 'Laravel' way to do this.
When using Many to Many relationships with Eloquent, the resulting model automatically gets a pivot attribute assigned. Through that attribute you're able to access pivot table columns.
Although by default there are only the keys in the pivot object. To get your columns in there too, you need to specify them when defining the relationship:
return $this->belongsToMany('Role')->withPivot('foo', 'bar');
Official Docs
If you need more help the task of configuring the relationships with Eloquent, let me know.
Edit
To query the price do this
$model->problems()->where('phone_problem', $problem->id)->first()->pivot->price
To get data from pivot table:
$price = $model->problems()->findOrFail($problem->id, ['phone_problem'])->pivot->price;
Or if you have many records with different price:
$price = $model->problems()->where('phone_problem', $problem->id)->firstOrFail()->pivot->price;
In addition.
To update data in the pivot you can go NEW WAY:
$model->problems()->sync([$problemId => [ 'price' => $newPrice] ], false);
Where the 2nd param is set to false meaning that you don't detach all the other related models.
Or, go old way
$model->problems()->updateExistingPivot($problemId, ['price' => $newPrice]);
And remind you:
To delete:
$model->problems()->detach($problemId);
To create new:
$model->problems()->attach($problemId, ['price' => 22]);
It has been tested and proved working in Laravel 5.1 Read more.
Laravel 5.8~
If you want to make a custom pivot model, you can do this:
Account.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Account extends Model
{
public function users()
{
return $this->belongsToMany(User::class)
->using(AccountUserPivot::class)
->withPivot(
'status',
'status_updated_at',
'status_updated_by',
'role'
);
}
}
AccountUserPivot.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
class AccountUserPivot extends Pivot
{
protected $appends = [
'status_updated_by_nice',
];
public function getStatusUpdatedByNiceAttribute()
{
$user = User::find($this->status_updated_by);
if (!$user) return 'n/a';
return $user->name;
}
}
In the above example, Account is your normal model, and you have $account->users which has the account_user join table with standard columns account_id and user_id.
If you make a custom pivot model, you can add attributes and mutators onto the relationship's columns. In the above example, once you make the AccountUserPivot model, you instruct your Account model to use it via ->using(AccountUserPivot::class).
Then you can access everything shown in the other answers here, but you can also access the example attribute via $account->user[0]->pivot->status_updated_by_nice (assuming that status_updated_by is a foreign key to an ID in the users table).
For more docs, see https://laravel.com/docs/5.8/eloquent-relationships (and I recommend press CTRL+F and search for "pivot")

Categories