samedi 8 juin 2019

Append new element to eloquent collection

I have two tables posts and photos. Each post has 5 photos. I want to list in view each post with one photo (profile pic), first picture.

    $published_post = Post::where('created_by',auth()->user()->id)->where('status','published')->get();

    $photo = Photo::where('post',$published_post->id)->get();

These two gives me two different collection. How can I add the first photo of a particular post to its array so in view I can display using a foreach loop.

This is how I want in view:

@foreach($published_post as $item)


@endforeach

I tried put and push, but doesn't seem to be working. Not sure how exactly does we append a new key value pair to an object.

My two models:

Schema::create('posts', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('title');
        $table->timestamps();
    });

    Schema::create('photos', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('image');
        $table->integer('post');
        $table->timestamps();
    });

class Post extends Model
{
    protected $table = 'posts';
}


class Photo extends Model
{
    protected $table = 'photos';
    protected $fillable = ['image', 'post'];
}



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2MyXlPq
via IFTTT

Aucun commentaire:

Enregistrer un commentaire