dimanche 14 février 2021

Get model values with adding specific items in Laravel

I'm using Laravel as an API, but have some troubles with getting posts with the specific updated value.

Here is my code. Any help to fix the code regarding both syntax and inefficiencies?

use Controller;
use Post;
use User;
use Comment;

class HomeController extends Controller{
    public function index(){
        $posts = $this->getPosts('home');

        return view('template', ['posts' = $posts]);
    }

    public function getPosts($slug){
        $posts = Post::where('slug', '=', $slug)->get();

        foreach($posts as &$post){
            $post->user = User::find($post->user_id);
            $post->comments = Comment::where('post_id', '=', $post->post_id)->get();

            foreach($post->comments as &$comment){
                $comment->user = User::find($comment->user_id);
            }
        }

        return $posts;
    }
}

Model

<?php

namespace Latchel;

use Latchel\Model;

class Post extends Model
{

    protected $table = 'post';

    protected $primaryKey = 'post_id';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'html', 'slug', 'user_id'
    ];
}


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire