Angular/Laravel display a models main image through a relationship

General Tech Bugs & Fixes 2 years ago

1 1 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 28 Aug 2022, this text provides information on Bugs & Fixes related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (1)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

 

I have a model named 'property'. Each property can have many photos, but can only have one main photo. I have a API function written that returns all properties, with all the photos via an eloquent relationship.

public function all(User $user)
{
    $properties = $user->properties()->get();

    if (!$user)
    {
        return response()->json(['error' => 'User does not exist'], 404);
    }

    if (!$properties)
    {
        return response()->json(['error' => 'No properties'], 200);
    }

    return response()->json($properties);
}

This returns to me a list of all properties created by a certain user, with an array of photos in JSON format.

I have a service in angular which gets all these photos.

Advert Service

getAllProperties(userId: number) {
    return this.http.get(this.baseUrl + userId + '/all');
  }

I then have a dashboard component where I link to this service functionality and display all the properties.

export class DashboardComponent implements OnInit {

  properties: Property[];

  constructor(private advertService: AdvertService, private alertify: AlertifyService) { }

  ngOnInit() {
    this.getAllProperties();
  }

  getAllProperties() {
    const user = JSON.parse(localStorage.getItem('user'));
    this.advertService.getAllProperties(user.id).subscribe((properties: Property[]) => {
      this.properties = properties;
    }, error => {
      this.alertify.error(error);
    });
  }
}

I then display all the adds in my html like so.

 class="container mt-5">
   class="row">
     *ngFor="let property of properties" class="col-lg-2 col-md-3 col-sm-6">
       class="card mb-4">
         class="card-img-wrapper">
           class="card-img-top" src="" alt="">
          

{{property.photos}}

class=
1 views
0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.

tuteehub community

Join Our Community Today

Ready to take your education and career to the next level? Register today and join our growing community of learners and professionals.

tuteehub community