Abdullah Al Shahed
Abdullah Al Shahed

Reputation: 89

General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into `products`..... in laravel-8

i am facing a problem is SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into products (name, detail, color, logo, image, updated_at, created_at) values (fdsf, sdf, #7536d3, 20210522184540.jpg, 20210522184540.JPG, 2021-05-22 18:45:40, 2021-05-22 18:45:40)). i want a user have meny products here is my ProductController.php

<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\Admin\StoreTagsRequest;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $products = Product::latest()->paginate(20);

        return view('products.index',compact('products'))

            ->with('i', (request()->input('page', 5) - 1) * 5);
    }

    function authapi(Request $request)
    {
        $user = User:: where('email', $request->email)->first();
        if(!$user || !Hash::check($request->password, $user->password)){
            return response([
                'message' => ['These credentials do not match our records.']
            ],404);
        }

        $token = $user -> createToken('my-app-token')->plainTextToken;

        $response = [
            'user' => $user,
            'token' => $token
        ];

        return response($response,201);
    }

    function all_app_jsons(){
        return Product::all();
    }

    function search_by_name($name){
        return Product::where('name','like','%'.$name.'%')->get();
    }

    function search_by_id($id){
        return Product::where('id',$id)->get();
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('products.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //$tag = Product::create($request->all());

        //return redirect()->route('admin.tags.index');
        $request->validate([
            'name' => 'required',
            'detail' => 'required',
            'color' => 'required',
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'logo' => 'required|mimes:jpeg,png,jpg,gif,svg|max:1024',
        ]);

        $input = $request->all();

        if ($image = $request->file('image')) {
            $destinationPath = 'image/';
            $profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
            $image->move($destinationPath, $profileImage);
            $input['image'] = "$profileImage";
        }

        if ($logo = $request->file('logo')) {
            $destinationPath = 'logo/';
            $profileLogo = date('YmdHis') . "." . $logo->getClientOriginalExtension();
            $logo->move($destinationPath, $profileLogo);
            $input['logo'] = "$profileLogo";
        }

        Product::create($input);

        return redirect()->route('products.index')
                        ->with('success','Product created successfully.');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function show(Product $product)
    {
        return view('products.show',compact('product'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function edit(Product $product)
    {
        return view('products.edit',compact('product'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Product $product)
    {
        $request->validate([
            'name' => 'required',
            'detail' => 'required',
            'color' => 'required'
        ]);

        $input = $request->all();

        if ($image = $request->file('image')) {
            $destinationPath = 'image/';
            $profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
            $image->move($destinationPath, $profileImage);
            $input['image'] = "$profileImage";
        }else{
            unset($input['image']);
        }

        if ($logo = $request->file('logo')) {
            $destinationPath = 'logo/';
            $profileLogo = date('YmdHis') . "." . $logo->getClientOriginalExtension();
            $logo->move($destinationPath, $profileLogo);
            $input['logo'] = "$profileLogo";
        }else{
            unset($input['logo']);
        }

        $product->update($input);

        return redirect()->route('products.index')
                        ->with('success','Product updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function destroy(Product $product)
    {
        $product->delete();

        return redirect()->route('products.index')
                        ->with('success','Product deleted successfully');
    }

    // function indextwo(){
    //     //return DB::select("select * from  products");
    //    //DB::table('products')->orderBy('id','desc')->first();
    //    return Product::orderBy('id', 'DESC')->first();
    // }

}

here is my model product.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 'detail', 'image','color','logo'
    ];

    public function user(){
        return $this->belongsTo(User::class);
    }
}

here is model user.php

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens;
    use HasFactory;
    use HasProfilePhoto;
    use Notifiable;
    use TwoFactorAuthenticatable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
        'two_factor_recovery_codes',
        'two_factor_secret',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'profile_photo_url',
    ];

    public function products(){
        return $this->hasMany(Product::class);
    }
}

here is product table

  public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('detail');
            $table->string('color');
            $table->string('image');
            $table->string('logo');
            $table->unsignedBigInteger('user_id');
            $table->timestamps();
        });
        Schema::table('products', function (Blueprint $table){
            $table->foreign('user_id')->references('id')->on('users');

        });
    }

Upvotes: 0

Views: 20780

Answers (4)

Arinzehills
Arinzehills

Reputation: 2329

make sure that $fillable in the model has the field 'user_id' like this

namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

protected $fillable = [
    'user_id',
    'name',
    'detail', 
    'image',
    'color',
    'logo'
];

public function user(){
    return $this->belongsTo(User::class);
}
}

Upvotes: 1

Hedayatullah Sarwary
Hedayatullah Sarwary

Reputation: 2844

I am using Laravel 8 and fixed this error through these two steps:

  1. Move the word from $guarded array to $fillable array in User Mode. You can put user_id in the $fillable array.

    Product 
    {
        fillable=[
            'user_id',
            ... // other attributes
        ];
    }
    

    Or

    Product 
    {
        guarded = [];
    }
    
  2. Config.database.php: 'strict' => false in the array of 'mysql'

Note: If your problem is not solved, in your product migration make user_id as nullable.

Upvotes: 4

Tayyab mehar
Tayyab mehar

Reputation: 621

You need to specify user with id while inserting your data

$data['user_id']=$user->id;

Or Make your column user_id Nullable inthe database.

Upvotes: 0

Amir Kaftari
Amir Kaftari

Reputation: 1524

in this case you must add user_id to $fillable property in Product Model. like this :

protected $fillable = [
    'name', 'detail', 'image','color','logo','user_id'
];

Done...

Upvotes: 2

Related Questions