3

I'm getting this errorarray_map(): Argument #2 should be an array when a user trying to create a product

I changed my code from this solutions How to make each authenticated user only see their own product, and now it gives me that error.

ProductController

class productController extends Controller
{

public function index(Request $request)
{
    $userId = $request->user()->id;
    $products = products_model::where('user_id', $userId)->get();
   return view('seller.product.index',compact('products'));
}




public function create()
{  
    return view('seller.product.create');
}

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


public function store(Request $request)
{

    $formInput=$request->except('image');
    $this->validate($request, [
     'pro_name'=> 'required',
     'pro_price'=> 'required',
     'pro_info'=> 'required',
     'user_id' => \Auth::id(),
     'image'=>'image|mimes:png,jpg,jpeg|max:10000'
    ]);

    $image=$request->image;
    if($image){
        $imageName=$image->getClientOriginalName();
        $image->move('images', $imageName);
        $formInput['image']=$imageName;
    }

    products_model::create($formInput);
    return redirect()->back();
}


public function show($id)
{
    //
}


public function edit($id)
{
    //
}


public function update(Request $request, $id)
{
    //
}


public function destroy($id)
{
   $userId = $request->user()->id();
   $deleteData=products_model::where('user_id', $userId)->findOrFail($id);
   $deleteData->delete();

   return redirect()->back();
}
}

Products_model

class products_model extends Model
{
protected $table='products';
protected $primaryKey='id';
protected $fillable= ['user_id','pro_name','pro_price','pro_info','image','stock','category_ id'];
}

Products table

class CreateProductsTable extends Migration
{

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('pro_name');
        $table->integer('pro_price');
        $table->text('pro_info');
        $table->integer('stock');
        $table->string('image')->nullable();
        $table->timestamps();

        $table->bigInteger('user_id')->unsigned()->index();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}


public function down()
{
    Schema::dropIfExists('products');
}
}

After updating my code now am getting this errorSQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert intoproducts(pro_name,pro_price,stock,pro_info,i`

2
  • What function is giving u this error? Commented Jun 7, 2019 at 21:33
  • @MateusJunges the store function. vendor/laravel/framework/src/Illuminate/Validation/ValidationRuleParser.php and highlights this line return array_map([$this, 'prepareRule'], $rule) Commented Jun 7, 2019 at 21:42

1 Answer 1

1

Change your validate function. Instead of use $this->validate(), use $request->validate() method:

$request->validate([
   'pro_name'=> 'required',
   'pro_price'=> 'required',
   'pro_info'=> 'required',
   'user_id' => 'required|integer',
   'image'=>'image|mimes:png,jpg,jpeg|max:10000'
]);

If the validation rules pass, your code will keep executing normally; however, if validation fails, an exception will be thrown and the proper error response will automatically be sent back to the user.

Another solution:

Add

use Validator;

to your class.

$validator = Validator::make($request->all(), [
    'pro_name'=> 'required',
    'pro_price'=> 'required',
    'pro_info'=> 'required',
    'user_id' => 'required|integer',
    'image'=>'image|mimes:png,jpg,jpeg|max:10000'
]);

if($validator->fails()){
    //Validation does not pass logic here
}else{
    //
}

One more: Create a form request, with

php artisan make:request RequestName

The file will be created in app\Http\Requests directory.

Within the file, add your rules to the rules method:

public function rules()
{
    return [
       'pro_name'=> 'required',
       'pro_price'=> 'required',
       'pro_info'=> 'required',
       'user_id' => 'required|integer',
    ];
}

Change the authorize method, to return true:

public function authorize()
{
    return true;
}

In your store method, swap the Request $request with RequestName $request. Now you don't need to validate the $request inside store method. It will go to store only if the validation succeed;

Your store method now should looks like

public function store(RequestName $request)
{
    $formInput=$request->except('image');

    $image=$request->image;
    if($image){
        $imageName=$image->getClientOriginalName();
        $image->move('images', $imageName);
        $formInput['image']=$imageName;
    }

    products_model::create(array_merge(
        $formInput, ['user_id' => Auth::user()->id]
    ));
    return redirect()->back();
}

Dont forget to use App\Http\Requests\RequestName

If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors. You can learn more about request validation here.

[EDIT] I change the users_id rule to user_id, to match with your foreign key name. I think you made a typo here when you asked the question.

Hope it helps.

Sign up to request clarification or add additional context in comments.

2 Comments

Comments are not for extended discussion; this conversation has been moved to chat.
@BhargavRao sorry about that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.