Noob User CakePhp I have a question - I am FR

Hello Cake PHP - last version,

I created a controller how can I return my request to my view

<?php

   namespace App\Controller;

   use App\Controller\AppController;

   class PostsController extends AppController {

   public function index() {

    /*$query = $this->Posts->find()
        ->select(['id', 'name', 'content'])
        ->where(['id !=' => 1])
        ->order(['date_post' => 'DESC']);*/

    $query = $this->Posts->find('all');

    $this->set(compact('posts'));

     foreach ($query as $post) {
        debug($post->name);
        debug($post->content);
     }
  }
}

I referred to the doc

I have my request May it runs above the template not in my container which is provided

if I put my foreach he said I do not know $query

I do not know where to look in the doc

sorry for English is translated with Google

You’re setting the variable $posts to view, but you have only defined $query, so that’s certainly a mistake.

It’s also important to understand that a query builder function like $this->Posts->find(‘all’) only creates an SQL query and does NOT execute it automatically.

To execute it, you can do something like:

$this->Posts->find()->all()

or:

$this->Posts->find()->toArray()

or you can loop through it with a foreach like you did at the bottom of your action.

So the proper code is:

<?php

   namespace App\Controller;

   use App\Controller\AppController;

   class PostsController extends AppController {

       public function index() {

           $posts = $this->Posts->find();

           $this->set(compact('posts'));
      }
}

And then in your view:

foreach ($posts as $post) {
     debug($post->name);
     debug($post->content);
}

Yes thank ali

i created :

    public function posts() {
    
    //query all posts
    $posts = $this->Posts->find('all');
    //pagination
    $this->set('posts', $this->paginate($posts));
    //retour du resultat
    $this->set(compact('posts'));
} 

and view single where get id :

public function single($id) {   
    
    $single = $this->Posts->get($id);
    $this->set(['single' => $single]);
   
}

is good for you in any case it works