phpcakephpcakephp-routing

When parameter is not passed to controller over url


In cakephp, I've a controller that should receive a parameter and then call model to work with database to show the result in a view. Pretty common mvc approach.

Imagine the controller as "Insert a new post" which should be associated to an specific user.

So, the URL should be: http://mysite/inspost/(user_id).

The problem is, when URL is like http://mysite/inspost/

It will show the same view and will insert the new post even if the user_id has not been specified.

How can I control this?


Solution

  • From the 2nd page of the blog tutorial, Adding a layer:

    public function view($id = null) {
        if (!$id) {
            throw new NotFoundException(__('Invalid post'));
        }
    
        $post = $this->Post->findById($id);
        if (!$post) {
            throw new NotFoundException(__('Invalid post'));
        }
        $this->set('post', $post);
    }