laravel-best-practices icon indicating copy to clipboard operation
laravel-best-practices copied to clipboard

Mass assigment

Open m-usman02 opened this issue 4 years ago • 4 comments

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()?

m-usman02 avatar Nov 09 '20 11:11 m-usman02

Rules are made to be broken

TraLeeee avatar Dec 07 '20 05:12 TraLeeee

@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');
}

Tpojka avatar Dec 07 '20 20:12 Tpojka

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');
}

Thifany-Nicastro avatar Dec 14 '20 12:12 Thifany-Nicastro

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.

JacekAndrzejewski avatar Sep 17 '21 10:09 JacekAndrzejewski