php - How to get product Id from hidden field Laravel

926

I'm trying to get theId of a product when I submit the form using the hidden input field but am getting an errorTrying to get property of non-object . How can I fix this issue?

code

Controller

class productController extends Controller
{

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index(Request $request)
{
    $userId = $request->user()->id;
    $products = product::where('admin', $userId)->get();
   return view('admin.product.index',compact('products'));
}



/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response
 */

public function admin()
{
   $products=product::all();
   return view('admin.product.index',compact('products'));
}

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request) 
{ 

    $formInput=$request->all();
    $image=array();
    if($files=$request->file('image')){
        foreach($files as $file){
            $name=$file->getClientOriginalName();
            $file->move('images',$name);
            $image[]=$name;

        }
       // dd($formInput);

    }

    //dd($formInput); 
    Image::create(array_merge($formInput,[
       // $id=$request->input('id'), 
       // $product=Product::find($id),
        $request->input('product_id'),
    ])); 
    return redirect()->back(); 

}

blade

   <form action="{{route('product.store')}}" method="post" 
   role="form" 
   enctype="multipart/form-data">
            {{csrf_field()}}
  @foreach ( $products as $product )
      <input type="hidden" name="product_id" value="{{ $product->id 
   }}" />
    @endforeach
    </form>

Any help will be appriciated.

406

Answer

Solution:

Looks like you have more than 1product_id hidden field.

If you plan to submit more than 1 add square brackets to then nameproduct_id[].

Request object should retrieve the same name. You are usingid in controller, but submittingproduct_id named field.

Use$request->input('product_id')

People are also looking for solutions to the problem: php - Getting the sum of columns in a Laravel raw select statement

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.