xyz
xyz

Reputation: 91

Get product id to store attachments accordingly

I currently have the add attachment button for each product on the product list page. After clicking the button, will proceed to add attachment form. How do I get the current product ID from the product table in order to store the attachment data into the attachment table?

Route

Route::post('/store/{product}', 'AttachmentController@store')->name('attachment.store');

Product Model

public function attachment()
{
    return $this->hasMany(Attachment::class, 'product_id', 'id');
}

Attachment Model

public function product()
{
    return $this->belongsTo(Product::class, 'product_id');
}

Controller

public function create()
{        
    return view('document.create', ['prod' => Product::select('id', 'name')->get()]);
}
public function store(Request $request, Product $product) {        
    
    $data['product_id'] = $product->id;

    $data = $request->validate([
        'file' => 'required',
        'file.*' => 'mimes:csv,xlsx,pdf,docx',
    ]);

    $attachmentData = [];   
    if($request->hasFile('file'))
    {
        foreach($request->file('file') as $file) {
            $path = public_path('storage/attachments/'.$request->product_id);
            $fileName = time().'-'.$file->getClientOriginalName();
            $file->move($path, $fileName);
            $attachmentData[] = $fileName;
        }
        $data['file'] = json_encode($attachmentData);
    }
    $attachment = Attachment::create($data);

    return redirect()->route('product.index')->with('success','Attachment added successfully');
}

Blade View

<form method="POST" action="{{route('attachment.store')}}" enctype="multipart/form-data">
    @csrf
    <h3><b>Add Attachment</b></h3>
    <input type="submit" class="btn btn-primary mr-2" value="Save">

    <div class="row">
        <h4 class="card-title">General</h4>

        <input type="text" name="product_id" value="{{ $product->id ?? '' }}" hidden>

        <div class="form-group">
            <label for="name">Name</label>
            <input type="text" id="name" class="form-control" name="name" required>
        </div>
        <div class="form-group">
            <label>Attachment </label>
            <div class="input-group-append">
                <label for="attachment" class="btn btn-info">Upload</label>
                <input id="attachment" type="file" name="file[]" multiple required>
            </div>
        </div> 
    </div>
</form>

Upvotes: 0

Views: 262

Answers (1)

A.A Noman
A.A Noman

Reputation: 5270

You have to use form action like below

<form method="POST" action="{{route('attachment.store',['product'=>$product->id])}}" enctype="multipart/form-data">

Upvotes: 1

Related Questions