Laravel blade access relationship with where condition

75 0 0 0

Last Updated : 2022-05-23 08:54:06

In this snippet I will teach you how to access relationship data in laravel blade files with where condition

Hello guys, 

In this snippet I will teach you how to get relationship data in laravel blade file with where condition 

First

you have to define the relation in your model relatioship like this


<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Project extends Model
{
use HasFactory;

##--------------------------------- RELATIONSHIPS
public function images() {
return $this->hasMany(Image::class, 'project_id', 'id');
}

public function cover() {
return $this->images()->where('cover', '1'); // this is the where condition you want
}

}

Second

In you blade file just access that cover image like below


<img src="{{ asset('storage/projects') }}/{{$project->cover[0]->name}}" class="img-fluid mb-3">

// NOTE THAT - to access that relationship use {{$project->cover[0]->name}}

Mahmoud Anwar

Mahmoud Anwar

Back End Developer with a passion for developing innovative web applications that expedite the efficiency and effectiveness of organizational success. Well-versed in technology and writing code to create systems that are reliable and user-friendly. Also has the proven ability to motivate, educate, and collaborate effectively to build web applications and effectively track changes. Confident communicator, strategic thinker, and innovative creator to develop software that is customized to meet a company’s organizational needs, highlight their core competencies, and further their success.