You can of course use the create method instead. However the upload part is a bit more tricky. Most developers would create a service class for it. Now you can call that class in your controller and just pass the file and the location for example
Dec 3, 2015
7
Level 3
Is there a bulletproof method for image upload and keep it as easy, as MyModel::create($request->all());
Hi all, I'm a Laravel newbie who would like to learn how to initially stick to best practices.
I've read a lot of image upload tutorials, but there is one thing that I can't make out. For example, here www.easylaravelbook.com/blog/2015/04/08/processing-file-uploads-with-laravel-5/ we have such piece of code:
$product = new Product(array(
'name' => $request->get('name'),
'sku' => $request->get('sku')
));
$product->save();
$imageName = $product->id . '.' .
$request->file('image')->getClientOriginalExtension();
$request->file('image')->move(
base_path() . '/public/images/catalog/', $imageName
);
return \Redirect::route('admin.products.edit',
array($product->id))->with('message', 'Product added!');
But is it correct? Do I really have to list all my model properties like this:
$product = new Product(array(
'name' => $request->get('name'),
'sku' => $request->get('sku')
));
But I have lots of them, and this looks like much more conveniently:
Work::create($request->all());
Do I miss anything important?
Level 80
@RStreignard You could do something like this:
// If create(), instantiate new model instance
$model = new ModelName;
// If update(), either use route–model binding to get model instance injected into controller action
// Or find model from database
$model = ModelName::findOrFail($id);
// Fill model with data from request
$model->fill($request->all());
// Do image upload logic…
$model->image_filename = $filename;
// Save model
$model->save();
As you can see, this works whether the model is being created or updated, so you can wrap everything from the fill() call in a service class.
class SaveModelWithImage
{
public function __construct(ModelName $model)
{
$this->model = $model;
}
public function save(Request $request)
{
$this->model->fill($request->all());
if ($request->hasFile('file_input_name')) {
$this->model->image_filename = $this->uploadFile($request->file('file_input_name'));
}
return $this->model->save();
}
protected function uploadImage(UploadedFile $file)
{
// TODO: Generate filename
// Move file to path of your choice
$file->move(storage_path('app'));
// Return generated filename
return $filename;
}
}
1 like
Please or to participate in this conversation.