Fixing the Add action in your controller to save the user_id

23666One of the key things youll do with cakephp is to ensure that when your saving data that the user logged in owns thats you save their user_id as well.

the simpliest way to do this is with one line of code added to your add action;

Sample Code from a Controller called Joke;

public function add()
{
$joke = $this->Jokes->newEntity();
if ($this->request->is('post')) {

$joke = $this->Jokes->patchEntity($joke, $this->request->data); 

// Added this line, set the userid to the logged in userĀ  $joke->user_id = $this->Auth->user('id');

if ($this->Jokes->save($joke)) {
$this->Flash->success(__('The joke has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The joke could not be saved. Please, try again.'));
}
}
$users = $this->Jokes->Users->find('list', ['limit' => 200]);
$jokescategories = $this->Jokes->Jokescategories->find('list', ['limit' => 200]);
$this->set(compact('joke', 'users', 'jokescategories'));
$this->set('_serialize', ['joke']);
}