Answer the question
In order to leave comments, you need to log in
How in Laravel 5.x to encapsulate file uploads for different entities, or at least within different actions in the controller?
Good afternoon!
There is a form _form.blade.php that is pulled by the view blade: create.blade.php and update.blade.php
...
{{ Form::file('photo') }}
<img src="/storage/images/articles/{{ $article->photo }}" style="height:50px" alt="">
...
class ArticlesController extends Controller
{
public function update(ArticleRequest $request, Article $article)
{
$request = $this->saveImage($request);
dump($request->all());
dump($request->photo);
$article->update($request->all());
dd($article->photo);
$this->syncTags($article, $request->input('tag_list'));
return redirect()->back();
}
private function saveImage(ArticleRequest $request)
{
if ($request->hasFile('photo')) {
$file = $request->file('photo'); // ->isValid()
$fileNameWithExt = $file->getClientOriginalName();
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extension = $file->getClientOriginalExtension();
$fileNameToStore = $filename . '_' . time() . '.' . $extension;
$file->storeAs('public/articles', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
$request->photo = $fileNameToStore;
return $request;
}
}
class ArticleRequest extends FormRequest{
...
public function rules()
{
return [
...
'photo'=>'image|nullable|max:1999'
...
];
}
...
}
Answer the question
In order to leave comments, you need to log in
BigDecimal will save you. And yes, with a double this is all the time. The example is not at the cash desk, but it is indicative.
Double toBeTruncated = new Double("3.5789055");
Double truncatedDouble = BigDecimal.valueOf(toBeTruncated)
.setScale(3, RoundingMode.HALF_UP)
.doubleValue();
I wouldn't do that.
The best solution in my opinion would be just feeding the UploadedFile object into the model being used. And in the model itself, use the setter of this attribute to intercept and convert the value.
It will look like this in the model:
public function setPhotoAttribute($value) {
if ($value instanceOf UploadedFile) {
$fileNameWithExt = $value->getClientOriginalName();
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extension = $value->getClientOriginalExtension();
$fileNameToStore = $filename . '_' . time() . '.' . $extension;
$file->storeAs('public/articles', $fileNameToStore);
return $this->attributes['photo'] = $fileNameToStore;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question