Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 1 year ago.
0

Try this.

// Article.php
public function scopeDescs($query, $LanguageID = null)
	{
		if($LanguageID)
			return $query->descriptions()->where('LanguageID',$LanguageID)->first();
		return $query->descriptions()->first();
	}

in controller

$article->descs($lang->LanguageID);
$article->descs();
0

Ty othmanus. I deleted "getDescriptionsAttribute" and copied this scope but: "Call to undefined method Illuminate\Database\Query\Builder::descriptions()". Descriptions is not a field, it's just a relationship. I did anything wrong?

I have a foreach of languages in my view and by each language I want to get $article->descs($language->id).

// Article.php (Model)
public function descriptions()
{
        return $this->hasMany('\App\Models\ArticleDescription',"ArticleID");
}

public function scopeDescs($query, $LanguageID = null)
{
        if($LanguageID)
            return $query->descriptions()->where('LanguageID','=',$LanguageID)->first();

        return $query->descriptions()->first();
}

//ArticleController
$article = Article::with('descriptions')->find($id);

//View
@foreach($languages as $language)
    <?php $description = $article->descs($language->id);?>
@endforeach

Ty for help.

Last updated 9 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

alexwut alexwut Joined 13 Mar 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.