PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 20, 2022

[FIXED] Query buider Laravel

 February 20, 2022     laravel-5     No comments   

Issue

I have a table to store my articles. I have no pictures in this table, and my photos are in another table. I have added 5 posts and each post has 3 pictures. Now I want to get 5 posts and each post only takes 1 out of 3 pictures of it, how to do ?? i need help, thanks

enter image description here

enter image description here


Solution

Use Laravel's relationship functions, Add this to your Post model:

public function images()
{
    return $this->hasMany(YourImageModel::class);
}

And for your query use this:

$post = Post::find($id)->with('images')->first();
$allImages = $post->images;
$firstImage = $post->images->first();

If you want all posts with images:

$posts = Post::with('images')->get();

In your blade:

@foreach($posts as $post)
    {{ $post->images->first() }}
@endforeach


Answered By - ibrahim-dogan
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing