laravel-best-practices
laravel-best-practices copied to clipboard
Mass assigment
Mass assignment I am still confused you showed saving validated() data with create is much good than what about image? if I have to upload a image and rename it according to my relevant path and how can I save it with validated()?
Rules are made to be broken
@ua3167
It's ok to make another method and modify data per need in request file:
// App\Http\Requests\Category\StoreCategory::class
/**
* Modify input data
*
* @return array
*/
public function getSanitized(): array
{
$sanitized = $this->validated();
//Add your code for manipulation with request data here
return $sanitized;
}
and then in controller apply
/**
* Store a newly created resource in storage.
*
* @param StoreCategory $request
* @return RedirectResponse|Redirector
*/
public function store(StoreCategory $request)
{
// Sanitize input
$sanitized = $request->getSanitized();
// Store the Category
$category = Category::create($sanitized);
return redirect('categories');
}
Don't know if it's a good approach, but I always used Traits for that
<?php
namespace App\Traits;
trait Uploadable
{
public function saveFile($request)
{
$file = $request->picture;
$fileName = time().'_'.$file->getClientOriginalName();
$file->storeAs('uploads', $fileName, 'public');
return $fileName;
}
}
then in controller
public function store(ProductRequest $request)
{
$validated = $request->validated();
$validated['picture'] = $this->saveFile($request);
Product::create($validated);
return redirect()->route('admin.products.index');
}
One thing to note: mutators work when mass assigning. Not that this would help in this case as renaming a file in mutator is a bad idea, but it would help in cases where you need to sanitize input.