You can use insertGetId method to get autoincrement Id when you insert a record.
May 16, 2015
8
Level 1
Getting ID of uploaded file
Hello guys, I am working on a simple file uploading and experiencing a small problem.
I have function addNewArticle which handles getting some data from the form and then inserting them into database via Eloquent. Now there is a field image_id which I need to fill with the ID of uploaded file/image. But I dont know how to get this ID? (When saving the image name and url into database, ID is set to autoincrement)
public function addNewArticle()
{
$data = array (
'title'=> Input::get('title'),
'content'=> Input::get('content'),
'image_id'=> how to get the ID of uploaded file???
);
Article::insertArticle($data);
Btw my form for handling upload looks something like this in my view:
{{ Form::open(array('action' => 'AdminController@addNewArticle','files' => true)) }}
blablabla
{{ Form::file('image') }}
Thank you
Level 52
@Mikaelo In your controller :
public function addNewArticle()
{
//getting the name of uploaded image
$name = Input::file('image')->getClientOriginalName();
//move the uploaded image
Input::file('image')->move('images', $name.rand(4,10).'.jpg');
//getting image data from article
$imagedata = array (
'name'=> $name,
'url'=> $name
);
//saving image data into Image eloquent model
$image_id = Image::insertImage($imagedata);
//getting article article
$data = array (
'title'=> Input::get('title'),
'content'=> Input::get('content'),
'image_id'=> $image_id)
);
//saving article data into Article eloquent model
Article::insertArticle($data)
return Redirect::to('admin')->with('message','Article was added successfully');
}
And in image model :
class Image extends Eloquent {
protected $fillable = array('url','name');
public $timestamps = true;
public function article()
{
return $this->hasMany('Article');
}
public static function insertImage($imagedata)
{
$image = new Image;
$image->fill($imagedata);
$image->save();
return $image->id;
}
Please or to participate in this conversation.