1
votes

I'm trying to get the hang of using Eloquent ORM so I'm creating a simple blog from scratch using Slim3/Twig. I've been successful in creating a User model and Post model that are linked to two tables(user table, post table) and have been able to insert blog post links dynamically into my 'home' twig template.

namespace App\Controllers;

use App\Models\User;
use App\Models\Post;
use Slim\Views\Twig as View;
use Illuminate\Database\Eloquent\Model;

class StoryListController extends Controller
{
  public function index($request, $response)
  {
    $posts = Post::join('users', 'posts.user_id', '=', 'users.id')->get();

    return $this->container->view->render($response, 'home.twig', [
      'posts' => $posts
    ]);
  }
}

Simple Blog list view

I've passed in a variable in to my routes so I can click on a blog post and have it render the view that corresponds with the right 'id'

$app->get('/', 'StoryListController:index')->setName('home');

$app->get('/stories/story/{postId}', 'StoryTemplateController:story')->setName('stories.story');

but for the life of me I haven't been able to correctly access that variable in my controller. This is what I've tried, not sure if I was heading in the right direction. Any help to get me going again is appreciated.

<?php

namespace App\Controllers;

use App\Models\User;
use App\Models\Post;
use Slim\Views\Twig as View;
use Illuminate\Database\Eloquent\Model;

class StoryTemplateController extends Controller
{
  public function story($request, $response, $postId)
  {
    $post = Post::join('users', 'posts.user_id', '=', 'users.id')->where('posts.id', '=', '{postId}')->with(['postId' => $postId])->get();
    return $this->container->view->render($response, '/stories/story.twig', [
      'post' => $post
    ]);
  }
}
1

1 Answers

0
votes

You can get at the postId from the Request's attribute:

$postId = $request->getAttribute('postId');

or by looking at the array of $args which is the third parameter passed to your route action:

$postid = $args['postId'];

Try this:

<?php

namespace App\Controllers;

use App\Models\User;
use App\Models\Post;
use Slim\Views\Twig as View;
use Illuminate\Database\Eloquent\Model;

class StoryTemplateController extends Controller
{
  public function story($request, $response, $args)
  {
    $postId = $requst->getAttribute('postId');
    // or $postId = $args['postId'];

    // rest of method
  }
}