I’m new to cakePHP, and I’m using cakePHP 2x. I’m doing a project where a user can upload multiple images using post. I have come so far but can’t upload the files.
This is the images table of my database:
post_id
is the foreign key. This is the post model:
<?php
class Post extends AppModel {
public $belongsTo = array('Catagory','User');
public $hasMany = array(
'Image' => array(
'className' => 'Image',
'foreignKey' => 'post_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
Now the Post controller:
public function addPost() {
if ($this->request->is('post')) {
// pr ($this->request->data);
//die();
$rootfolder = WWW_ROOT . 'img/uploads/' ;
if(!empty($this->request->data))
{
//Check if image has been uploaded
if(!empty($this->request->data['Post']['Image']))
{
foreach ($this->request->data['Post']['Image'] as $i => $image)
{
$file = $this->request->data['Post']['Image'][$i];
$tmp = $file['tmp_name'];
// debug( $file);
// debug( $tmp );
// die();
$ext = substr(strtolower(strrchr($file['name'], '.')), 1);
//get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
//only process if the extension is valid
if(in_array($ext, $arr_ext))
{
$name = substr(md5(time()), 0,10).$i.'.'.$ext;
$path = $rootfolder.$name;
debug($name);
debug($path);
// die();
move_uploaded_file($tmp,$path);
$file = array('name'=>$file['name'],'path' => $path );
debug($file);
$images[] = $file;
// $this->data['Post']['image']['name'] = $file['name']
// $this->Post->data['Image']['image'];
// $this->data->Post['Image']['image'] = $file['name'];
}
}
debug($images);
// die();
//now do the save (optional)
} //if($this->Image->save($this->data)) {...} else {...}
}
$this->Post->create();
// the save() method will check for validation errors and abort the save if any occur
// pr ($this->request->data);
// die();
$this->request->data['Post']['user_id'] = AuthComponent::user('id');
if ($this->Post->saveAll($this->request->data)) {
$this->Flash->success(__('Your post has been saved.'));
// redirect function redirects to another URL
return $this->redirect(array('action' => 'index'));
}
$this->Flash->error(__('Unable to add your post.'));
}
$catagories = $this->Post->Catagory->find('list');
$this->set(compact('catagories'));
$image = $this->Post->Image->find('list');
$this->set(compact('image'));
}
Can anyone help me to complete these? Thank you.