Laravel general error 1364 field

I'm staring with Laravel and I'm having troubles trying to make a simple insert, but It seems that all of my fillable fields are not being included. This is the error: SQLSTATE[HY000]: General err...

I’m staring with Laravel and I’m having troubles trying to make a simple insert, but It seems that all of my fillable fields are not being included. This is the error:

SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a default value 
(SQL: insert into `addresses` (`updated_at`, `created_at`) 
values (2017-12-25 09:31:49, 2017-12-25 09:31:49))

As you can see, only created_at and updated_at are about to be inserted, I thought that maybe I forgot my fillable vars, but this is my Model:

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Addresses extends Model
{

protected $fillable = [
    'name',
    'city',
    'suburb',
    'street',
    'o_number',
    'i_number',
    'postal_code',
    'phone_s',
    'email_s',
    'google_map',
    'customer_id'
];

}

And the Controller

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppAddresses;
use AppCustomers;

class AddressesController extends Controller
{
public function __construct()
{
    $this->middleware('auth');
}

public function store(Request $request){

    $create = Addresses::create([
        'name' => request('name'),
        'city' => request('city'),
        'suburb' => request('suburb'),
        'street' => request('street'),
        'o_number' => request('o_number'),
        'i_number' => request('i_number'),
        'postal_code' => request('postal_code'),
        'phone_s' => request('phone_s'),
        'email_s' => request('email_s'),
        'google_map' => request('google_map'),
        'customer_id' => Customers::where('code',$request->session()->get('customer_code'))->first()->id
    ]);

    $success = $create ? $request->session()->flash('success', '¡Registro exitoso!') : $request->session()->flash('success', 'Ooops! Algo salio mal :(');

    return redirect('addresses/'.$request->session()->get('customer_code'));
 }
}

Echo the request() values works! So I’m missing right now, I have some other Models and Controller working good in the same way. Please Help!

I’m staring with Laravel and I’m having troubles trying to make a simple insert, but It seems that all of my fillable fields are not being included. This is the error:

SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a default value 
(SQL: insert into `addresses` (`updated_at`, `created_at`) 
values (2017-12-25 09:31:49, 2017-12-25 09:31:49))

As you can see, only created_at and updated_at are about to be inserted, I thought that maybe I forgot my fillable vars, but this is my Model:

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Addresses extends Model
{

protected $fillable = [
    'name',
    'city',
    'suburb',
    'street',
    'o_number',
    'i_number',
    'postal_code',
    'phone_s',
    'email_s',
    'google_map',
    'customer_id'
];

}

And the Controller

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppAddresses;
use AppCustomers;

class AddressesController extends Controller
{
public function __construct()
{
    $this->middleware('auth');
}

public function store(Request $request){

    $create = Addresses::create([
        'name' => request('name'),
        'city' => request('city'),
        'suburb' => request('suburb'),
        'street' => request('street'),
        'o_number' => request('o_number'),
        'i_number' => request('i_number'),
        'postal_code' => request('postal_code'),
        'phone_s' => request('phone_s'),
        'email_s' => request('email_s'),
        'google_map' => request('google_map'),
        'customer_id' => Customers::where('code',$request->session()->get('customer_code'))->first()->id
    ]);

    $success = $create ? $request->session()->flash('success', '¡Registro exitoso!') : $request->session()->flash('success', 'Ooops! Algo salio mal :(');

    return redirect('addresses/'.$request->session()->get('customer_code'));
 }
}

Echo the request() values works! So I’m missing right now, I have some other Models and Controller working good in the same way. Please Help!

Hi I am trying to insert data into db but it says:

SQLSTATE[HY000]: General error: 1364 Field ‘title’ doesn’t have a
default value (SQL: insert into projects (owner_id, updated_at,
created_at) values (1, 2019-06-28 13:17:11, 2019-06-28 13:17:11))

I am following Laracasts Laravel from scratch tutorial

controller:

      public function store()
      {
        $attributes = $this->validateProject();
        $attributes['owner_id'] = auth()->id();
        $project = Project::create($attributes);

    //Project::create($attributes);
    //Project::create(request(['title', 'description']));

          Mail::to($project->owner->email)->send(
            new ProjectCreated($project)
          );

        return redirect('/projects');
      }

model:

  protected $guarded = [];

table:

      Schema::create('projects', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('owner_id');
        $table->string('title');
        $table->text('description');
        $table->timestamps();

        $table->foreign('owner_id')->references('id')->on('users')->onDelete('cascade');
    });

blade file:

   <form method="POST" action="/projects">
   @csrf
   <div class="field">
    <label class="label" for="title">Title</label>
    <div class="control">
        <input type="text" class="input {{ $errors->has('title') ? 'is-danger' : ''}}" name="title" value="{{ old('title') }}" placeholder="Project title">
    </div>
    </div>
    <div class="field">
      <label class="label" for="title">Description</label>
      <div class="control">
        <textarea name="description" class="textarea {{ $errors->has('description') ? 'is-danger' : ''}}" placeholder="Project description">{{ old('description') }}</textarea>
    </div>
   </div>
      <div class="field">
      <div class="control">
        <button type="submit" class="button is-link">Create Project</button>
        </div>
    </div>

   @include('errors')

  </form>

how to solve this issue

Lizesh Shakya's user avatar

asked Jun 28, 2019 at 13:32

pro's user avatar

6

You have the field title on the projects table however you are not assigning it a value. As it is set as Not Nullable this will give this error.

You will need all attributes to be in the $fillable attribute on the model when using Project::create($attributes); which you do not seem to have.

An example of the $fillable would be :

protected $fillable = [
    'title',
    'description',
    'owner_id',
];

There are several other potential causes however it is impossible to tell without you including your full Project model and the view which this request is from.

Edit

You will need to change your function to this :

public function store(ProjectRequest $request)
  {
    $attributes = $request->all();
    $attributes['owner_id'] = auth()->id();
    $project = Project::create($attributes);

      Mail::to($project->owner->email)->send(
        new ProjectCreated($project)
      );

    return redirect('/projects');
  }

You can create the ProjectRequest class by running php artisan make:request ProjectRequest and then putting your validation rules in there instead.

Read more here.

answered Jun 28, 2019 at 13:37

Kyle Wardle's user avatar

Kyle WardleKyle Wardle

8287 silver badges23 bronze badges

5

Add your column name in fillable like this in your model (I guess your model name is Project.php)

So your model class should like this.

<?php

mnamespace App;

use IlluminateDatabaseEloquentModel;

class Project extends Model
{
protected $guarded = [];
protected $fillable = [
    'title', 'owner_id','description'
];
public function owner()
{
    return $this->belongsTo(User::class);
}

public function tasks()
{
    return $this->hasMany(Task::class);
}

public function addTask($task)
{
    $this->tasks()->create($task);
}
}

And then update your controller store method like this.

public function store(Request $request)
  {
    $attributes = $this->validateProject();
    $attributes->owner_id = auth()->id();
    $attributes->title = $this->request->title;
    $attributes->description= $this->request->description;
    $project = Project::create($attributes);

      Mail::to($project->owner->email)->send(
        new ProjectCreated($project)
      );

    return redirect('/projects');
  }

answered Jun 28, 2019 at 13:37

Fokrule's user avatar

FokruleFokrule

8342 gold badges10 silver badges29 bronze badges

8

The error itself is self explanatory, check this code:

$attributes['owner_id'] = auth()->id();
$project = Project::create($attributes);

here you are creating a new record in project table, and for that you are taking only one column i.e. owner_id, but in the table there is a column title which do not have a default value.
So either take all the column while creating a new record or provide those column a default value (null or something else).

To set null as default value in migration:

$table->string('title')->nullable();

or you can directly change the column in database and set its default value as null, see the below screenshot:

enter image description here

answered Jun 28, 2019 at 13:51

Mayank Pandeyz's user avatar

Mayank PandeyzMayank Pandeyz

25.3k4 gold badges37 silver badges58 bronze badges

1

Unable to trace the problem you are facing. Give this code a try and please comment if you got any problem.

Inside your route file

Route::post('project', 'ProjectController@store')->name('project.store');

In your create view

<form method="POST" action="{{route('project.store')}}">
    @csrf
    <div class="field">
        <label class="label" for="title">Title</label>
        <div class="control">
            <input type="text" class="input {{ $errors->has('title') ? 'is-danger' : ''}}" name="title"
                   value="{{ old('title') }}" placeholder="Project title">
        </div>
    </div>
    ...
    <div class="field">
        <div class="control">
            <button type="submit" class="button is-link">Create Project</button>
        </div>
    </div>

    @include('errors')

</form>

In your ProjectController

namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppPost;

class UserController extends Controller{
    public function store(Request $request)
    {
        $this->validate($request, [
            'title' => 'required|max:255',
        ]);

        $post = Post::create([
                    'title' => $request->title,
                    'owner_id' => auth()->id()
                    ]);

    return redirect('/projects');
  }

EDIT 1

In your previous code inside ProjectsController, instead of using $attributes try using

public function store()
    {
        $project = Project::create([
            'title' => request('title'),
            'owner_id' => request('owner_id')
        ]);

        Mail::to($project->owner->email)->send(
            new ProjectCreated($project)
        );

        return redirect('/projects');
    }

EDIT 2

Instead of using create method, try this one

public function store()
{
        $project = new Project();
        $project->title = request('title');
        $project->owner_id = request('owner_id');
        $project->save();
...
}

answered Jun 28, 2019 at 17:59

Lizesh Shakya's user avatar

Lizesh ShakyaLizesh Shakya

2,3621 gold badge17 silver badges40 bronze badges

7

Today We are Going To Solve SQLSTATE[HY000]: General error: 1364 Field ‘name’ doesn’t have a default value laravel 5.5 in Php. Here we will Discuss All Possible Solutions and How this error Occurs So let’s get started with this Article.

Contents

  • 1 How to Fix SQLSTATE[HY000]: General error: 1364 Field ‘name’ doesn’t have a default value laravel 5.5 Error?
    • 1.1 Solution 1 : Change your config/database.php
    • 1.2 Solution 2 : Edit your migration script
    • 1.3 Solution 3 : Add the below code
  • 2 Conclusion
    • 2.1 Also Read These Solutions
  1. How to Fix SQLSTATE[HY000]: General error: 1364 Field ‘name’ doesn’t have a default value laravel 5.5 Error?

    To Fix SQLSTATE[HY000]: General error: 1364 Field ‘name’ doesn’t have a default value laravel 5.5 Error just Change your config/database.php. to solve this issue you have to just change your config/database.php in the connections.mysql section by putting ‘strict’ => false. this will help you to solve the issue. Try it!

  2. SQLSTATE[HY000]: General error: 1364 Field ‘name’ doesn’t have a default value laravel 5.5

    To Fix SQLSTATE[HY000]: General error: 1364 Field ‘name’ doesn’t have a default value laravel 5.5 Error just Edit your migration script. Just edit your migration script and put default value on this field to solve the issue. You can learn it better by given the below example. I hope this will help you. $table->string('name')->default('');

Solution 1 : Change your config/database.php

to solve this issue you have to just change your config/database.php in the connections.mysql section by putting ‘strict’ => false. this will help you to solve the issue. Try it!

Solution 2 : Edit your migration script

Just edit your migration script and put default value on this field to solve the issue. You can learn it better by given the below example. I hope this will help you.

$table->string('name')->default('');

Solution 3 : Add the below code

To solve this error just add the below one to your migration file. It will help you.

$table->string('name')->nullable();

Conclusion

So these were all possible solutions to this error. I hope your error has been solved by this article. In the comments, tell us which solution worked? If you liked our article, please share it on your social media and comment on your suggestions. Thank you.

Also Read These Solutions

  • no python at “C:UsersAccountNameAppDataLocalProgramsPythonPython38-32python.exe” error in VsCode
  • Jest: Cannot spy the property because it is not a function; undefined given instead
  • Javascript ES6 TypeError: Class constructor Client cannot be invoked without ‘new’
  • TypeError: can only concatenate str (not “NoneType) to str”
  • Cannot load configuration class error spring boot

Содержание

  1. SQLSTATE[HY000]: General error: 1364 Field ‘name’ doesn’t have a default value #2764
  2. Comments
  3. What I did
  4. What I expected to happen
  5. What happened
  6. What I’ve already tried to fix it
  7. Backpack, Laravel, PHP, DB version
  8. Sqlstate hy000 general error 1364 field laravel
  9. Sqlstate hy000 general error 1364 field laravel
  10. Sqlstate hy000 general error 1364 field laravel

SQLSTATE[HY000]: General error: 1364 Field ‘name’ doesn’t have a default value #2764

What I did

Want to create categories with its parent.

What I expected to happen

To store normally in database

What happened

SQLSTATE[HY000]: General error: 1364 Field ‘name’ doesn’t have a default value (SQL: insert into categories ( parent_id , updated_at , created_at ) values (2, 2020-05-04 18:13:42, 2020-05-04 18:13:42))

It writes this error but simultaniously inserts in database with name slug and parent, that means everything is working just getting this error

What I’ve already tried to fix it

I tried to put in BackpackCRUDappHttpControllersOperationsCraeteOperation
dd($request); in store() function and output was

Meaning that request does have name and slug attribute so I can not understand why I am getting this error.

Backpack, Laravel, PHP, DB version

When I run php artisan backpack:version the output is: 4.0, 7.9.2 , 7.3.1

The text was updated successfully, but these errors were encountered:

Hello there! Thanks for opening your first issue on this repo!

Just a heads-up: Here at Backpack we use Github Issues only for tracking bugs. Talk about new features is also acceptable. This helps a lot in keeping our focus on improving Backpack. If you issue is not a bug/feature, please help us out by closing the issue yourself and posting in the appropriate medium (see below). If you’re not sure where it fits, it’s ok, a community member will probably reply to help you with that.

Backpack communication channels:

  • Bug Reports, Feature Requests — Github Issues (here);
  • Quick help (How do I do X) — Gitter Chatroom;
  • Long questions (I have done X and Y and it won’t do Z wtf) — Stackoverflow, using the backpack-for-laravel tag;
  • Showing off something you’ve made, asking for opinion on Backpack/Laravel matters — Reddit;

Please keep in mind Backpack offers no official / paid support. Whatever help you receive here, on Gitter, Slack or Stackoverflow is thanks to our awesome awesome community members, who give up some of their time to help their peers. If you want to join our community, just start pitching in. We take pride in being a welcoming bunch.


Justin Case
The Backpack Robot

Looks like this is a support request, not a bug/feature. Could you please repost on StackOverflow, using the backpack-for-laravel tag?

Background: Here at Backpack we use Github Issues only for tracking bugs and features, not individual implementation issues. This helps a lot in keeping our focus on improving Backpack. Thanks a lot for understanding!

Here are all the Backpack communication mediums:

  • Long questions (I have done X and Y and it won’t do Z wtf) — Stackoverflow, using the backpack-for-laravel tag; this is recommended for most questions, since other developers can then find the answer on a simple Google search; also, people get points for answering — and who doesn’t like StackOverflow points?!
  • Quick help (How do I do X) — Gitter Chatroom;
  • Bug Reports, Feature Requests — Github Issues (here);

Please keep in mind Backpack offers no official / paid support. Whatever help you receive here, on Gitter, Slack or StackOverflow is thanks to our awesome awesome community members, who give up some of their time to help their peers. If you want to join our community, just start pitching in. We take pride in being a welcoming bunch.


Justin Case
The Backpack Robot

PS. In case I mistakenly closed your issue, yell 🙂 I’m a robot, I make mistakes.

Источник

Sqlstate hy000 general error 1364 field laravel

SQLSTATE[HY000]: General error: 1364 Field ‘category_id’ doesn’t have a default value (SQL: insert into products . » n

Initially i was adding these products without under any category than it was working and now its not adding under Category. n

can anyone would prefer to provide me its solution? n

here is my form: n

here is ProductsController: n

public function addProduct(Request $request)n <n if ($request->isMethod(‘post’))n <n $data = $request->all();nn $product = new Product;n $product->product_name = $data[‘product_name’];n $product->product_code = $data[‘product_code’];n $product->product_color = $data[‘product_color’];n if ( ! empty($data[‘description’]))n <n $product->description = $data[‘description’];n >n elsen <n $product->description = »;n >n $product->price = $data[‘price’];nn // Upload Imagen if ($request->hasFile(‘image’))n <n $image_tmp = Input::file(‘image’);n if ($image_tmp->isValid())n <n $extension = $image_tmp->getClientOriginalExtension();n $filename = rand(111, 99999) . ‘.’ . $extension;n $large_image_path = ‘images/backend_images/products/large/’ . $filename;n $medium_image_path = ‘images/backend_images/products/medium/’ . $filename;n $small_image_path = ‘images/backend_images/products/small/’ . $filename;n // Resize Imagesn Image::make($image_tmp)->save($large_image_path);n Image::make($image_tmp)->resize(600, 600)->save($medium_image_path);n Image::make($image_tmp)->resize(300, 300)->save($small_image_path);n // Store image name in products tablen $product->image = $filename;n >n >nn $product->save();nn /*return redirect()->back()->with(‘flash_message_success’,’Product has been added n successfully!’);*/nn return redirect(‘/admin/view-products’)->with(‘flash_message_success’, ‘Product has been n added successfully!’);n >nn $categories = Category::where([‘parent_id’ => 0])->get();n $categories_drop_down = » Select «;nn foreach ($categories as $cat)n <n $categories_drop_down .= » id . «‘>» . $cat->name . » «;n $sub_categories = Category::where([‘parent_id’ => $cat->id])->get();n foreach ($sub_categories as $sub_cat)n <n $categories_drop_down .= » id . «‘>  — » . n $sub_cat->name . » «;n >n >nn return view(‘admin.products.add_product’)->with(compact(‘categories_drop_down’));n >n n»,»body_in_markdown»:»I’m new to Laravel and trying to add Product under Category but when I add Product then it shows this error:nnSQLSTATE[HY000]: General error: 1364 Field ‘category_id’ doesn’t have a default value (SQL: insert into products . »nnInitially i was adding these products without under any category than it was working and now its not adding under Category.nncan anyone would prefer to provide me its solution?nnhere is my form:nn << csrf_field() >>n

I think it has something to do with the fillable in your Product model. n

Try to add this in your Product.php: n

You don’t inform about the category_id when you fill your model. n

if ($request->isMethod(‘post’))n <n $data = $request->all();nn $product = new Product;n $product->product_name = $data[‘product_name’];n $product->product_code = $data[‘product_code’];n $product->product_color = $data[‘product_color’];n $product->category_id = $data[‘category_id’]; // n

public function addProduct(Request $request)n <n if ($request->isMethod(‘post’))n <n $data = $request->all();nn $product = new Product;n $product->product_name = $data[‘product_name’];n $product->product_code = $data[‘product_code’];n $product->product_color = $data[‘product_color’];n $product->category_id = $data[‘category_id’]; // description = $data[‘description’];n >n elsen <n $product->description = »;n >n $product->price = $data[‘price’];nn // Upload Imagen if ($request->hasFile(‘image’))n <n $image_tmp = Input::file(‘image’);n if ($image_tmp->isValid())n <n $extension = $image_tmp->getClientOriginalExtension();n $filename = rand(111, 99999) . ‘.’ . $extension;n $large_image_path = ‘images/backend_images/products/large/’ . $filename;n $medium_image_path = ‘images/backend_images/products/medium/’ . $filename;n $small_image_path = ‘images/backend_images/products/small/’ . $filename;n // Resize Imagesn Image::make($image_tmp)->save($large_image_path);n Image::make($image_tmp)->resize(600, 600)->save($medium_image_path);n Image::make($image_tmp)->resize(300, 300)->save($small_image_path);n // Store image name in products tablen $product->image = $filename;n >n >nn dd($request->all(), $product); // save();nn//[. ]nn n

You can maybe check in the Product if you have the category_id attribute, and if yes. I don’t understand the error you get. n

product model : n

The App\Product file, not the method in probably your category model. n

But with what you show, you can try n

public function addProduct(Request $request)n <n if ($request->isMethod(‘post’))n <n $data = $request->all();n $category = \App\Category::findOrFail($data[‘category_id’]); // product_name = $data[‘product_name’];n $product->product_code = $data[‘product_code’];n $product->product_color = $data[‘product_color’];nn if ( ! empty($data[‘description’]))n <n $product->description = $data[‘description’];n >n elsen <n $product->description = »;n >n $product->price = $data[‘price’];nn // Upload Imagen if ($request->hasFile(‘image’))n <n $image_tmp = Input::file(‘image’);n if ($image_tmp->isValid())n <n $extension = $image_tmp->getClientOriginalExtension();n $filename = rand(111, 99999) . ‘.’ . $extension;n $large_image_path = ‘images/backend_images/products/large/’ . $filename;n $medium_image_path = ‘images/backend_images/products/medium/’ . $filename;n $small_image_path = ‘images/backend_images/products/small/’ . $filename;n // Resize Imagesn Image::make($image_tmp)->save($large_image_path);n Image::make($image_tmp)->resize(600, 600)->save($medium_image_path);n Image::make($image_tmp)->resize(300, 300)->save($small_image_path);n // Store image name in products tablen $product->image = $filename;n >n >nn // $product->save(); products()->save($product);nn//[. ]n n

Call to undefined method App\Category::products()n n

public function categories()<n return $this->hasMany(‘App\Category’,’parent_id’);n>n n

product model: n

You have to inverse both method. n

Add product (and named it products ) to Category, and category (instead of categories ) to your product model. n

And give us all the text please. it usually begins with n

hasMany(‘App\Category’,’parent_id’);n >n >n n

Источник

Sqlstate hy000 general error 1364 field laravel

public function up()n <n Schema::create(‘users’, function (Blueprint $table) <n $table->id();n $table->string(‘name’);n $table->string(’email’)->unique();n $table->timestamp(’email_verified_at’)->nullable();n $table->string(‘password’)->nullable();;n $table->rememberToken();n $table->timestamps();n >);n >nn n

You do not have to specify id, it is autogenerated. n

So when you create user you only need: n

$u = new User;n$u->name = ‘somename’;n$u->email = ‘someemail@test.test’;n$u->password = Hash::make(‘somepassword’);n$u->save();n n

That’s it! n»,»bodyInMarkdown»:»@vironeer nnYou do not have to specify id, it is autogenerated.nnSo when you create user you only need:nn«`n$u = new User;n$u->name = ‘somename’;n$u->email = ‘someemail@test.test’;n$u->password = Hash::make(‘somepassword’);n$u->save();n«`nnThat’s it!»,»replies»:[<«id»:681118,»conversation_id»:151387,»body»:»

I’m doing it like that n

i don’t understand, what is the SQL block code for? n

are you missing some code in the SQL block ? n

The id row should look lilke this n

i don’t understand, what is the SQL block code for? n

are you missing some code in the SQL block ? n

Laravel 9 is here, and along with it comes a wide array of useful new features and tweaks. This includes an improved accessor/mutator API, better support for Enum casting, forced scope bindings, a new database engine for Laravel Scout, and so much more.

Источник

Sqlstate hy000 general error 1364 field laravel

public function validationRules() <n return [n ‘name’ =>‘required’,n ’email’ => ‘required|email|unique:users,email’,n ‘password’ => ‘required|min:6’,n ];n >nn n

Patient model n

npublic function validationRules() <n return [n ‘first_name’ =>‘required’, n ‘last_name’ => ‘required’,n ‘address’ => ‘required’,n ‘date_of_birth’ => ‘required’,n ‘phone_no’ => ‘required’,n ‘image’ => ‘required’,n ‘medical_history’ => ‘required’,n ‘sex’ => ‘required’,n ‘blood_group’ => ‘required’,n ];nn if($request->hasFile(‘image’)) <nn $fileNameWithExt = $request->file(‘image’)->getClientOriginalName();n $fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);n $fileSize = $request->file(‘image’)->getSize();n $fileExt = $request->file(‘image’)->getClientOriginalExtension();n $fileNameNew = uniqid(», true) . time() . ‘.’ . $fileExt;nn >n >nn n

It means your User’s «name» field is null. A null is being passed and the user tables «name» field can not be null. n

why are you updating users information using PatientControlller? n

When you use controller function n

public function update(Request $request, User $user ,Patient $patient)n <n n

You are not passing any data to the user model. n

or manually one by one n

$user->update([n ‘name’ => $userValidData[‘name’],n . n]);n n

Schema::create(‘patients’, function (Blueprint $table) <n $table->increments(‘id’);n $table->string(‘first_name’);n $table->string(‘last_name’);n $table->string(‘address’);n $table->string(‘date_of_birth’);n $table->string(‘phone_no’);n $table->string(‘image’);n $table->boolean(‘sex’);n $table->string(‘blood_group’);n $table->mediumText(‘problem’)->nullable();n $table->mediumText(‘medical_history’);n n $table->integer(‘user_id’)->unsigned();n $table->foreign(‘user_id’)->references(‘id’)->on(‘users’)n ->onUpdate(‘cascade’)->onDelete(‘cascade’);nn $table->timestamps();n >);n n

//user migration n

$table->increments(‘id’);n $table->string(’email’)->unique();n $table->string(‘password’);n $table->string(‘role_id’)->default(’10’);//patientn $table->rememberToken();n $table->timestamps();n >);n n n

public function validationRules() <n return [n ’email’ =>‘required|email’,n ‘password’ => ‘required|min:6’,n ‘role_id’ => ‘required’ ,n ];n n >nnpublic function patient()n <n return $this->hasOne(‘App\Patient’);n >nn n

Patient Model n

public function validationRules() <n return [n ‘first_name’ =>‘required’, n ‘last_name’ => ‘required’,n ‘address’ => ‘required’,n ‘date_of_birth’ => ‘required’,n ‘phone_no’ => ‘required’,n ‘image’ => ‘required’,n ‘medical_history’ => ‘required’,n ‘sex’ => ‘required’,n ‘blood_group’ => ‘required’,n ];nn if($request->hasFile(‘image’)) <nn $fileNameWithExt = $request->file(‘image’)->getClientOriginalName();n $fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);n $fileSize = $request->file(‘image’)->getSize();n $fileExt = $request->file(‘image’)->getClientOriginalExtension();n $fileNameNew = uniqid(», true) . time() . ‘.’ . $fileExt;nn >n >nn n

npublic function edit(Patient $patient , User $user)n <n return view(‘Dashboard.default.patients.edit’, compact(‘patient’ , ‘user’ ));n >n /**n * Update the specified resource in storage.n *n * @param \Illuminate\Http\Request $requestn * @param \App\Patient $patientn * @return \Illuminate\Http\Responsen */n public function update(Request $request, User $user ,Patient $patient)n <n // User Validationn $userValidData = $request->validate($user->validationRules());nn // Patient Validationn $patientValidData = $request->validate($patient->validationRules());nn // save user datan $userValidData[‘role_id’] = ’10’;n $user->update($userValidData);n n $patientValidData[‘user_id’] = $patient->user->id;n $patient->update($patientValidData);nn $success = ‘the patient has been updated successfully’;n return redirect(‘/patients’)->with(‘success’, $success);n n>nn n

public function update(Request $request, User $user ,Patient $patient)n n

How do you expect $user to be loaded with the correct user? n

If you just mean the current user then change the controller; n

Источник

Bug report

What I did

Want to create categories with its parent.

Migration:

Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug')->unique();
            $table->integer('parent_id')->unsigned()->nullable();
            $table->timestamps();
        });

Model:

protected $fillable = ['name', 'slug', 'parent_id'];
public function children()
    {
        return $this->hasMany('AppModelsCategory', 'parent_id');
    }

Controller:

protected function setupCreateOperation()
    {
        $this->crud->setValidation(CategoryRequest::class);

        // TODO: remove setFromDb() and manually define Fields
        $this->crud->addField(['name' => 'name', 'type' => 'text', 'label' => 'Name']);
        $this->crud->addField(['name' => 'slug', 'type' => 'text', 'label' => 'Slug']);
        $this->crud->addField(['name' => 'parent_id', 'type' => 'select2', 'label' => 'Parent Category', 'entity' => 'children', 'attribute' => 'slug']);
    }

What I expected to happen

To store normally in database

What happened

SQLSTATE[HY000]: General error: 1364 Field ‘name’ doesn’t have a default value (SQL: insert into categories (parent_id, updated_at, created_at) values (2, 2020-05-04 18:13:42, 2020-05-04 18:13:42))

It writes this error but simultaniously inserts in database with name slug and parent, that means everything is working just getting this error

What I’ve already tried to fix it

I tried to put in BackpackCRUDappHttpControllersOperationsCraeteOperation
dd($request); in store() function and output was

#parameters: array:6 [▼
      "_token" => "JtVZd8Ejcomf6khWHQgMeDbtE9towuqO4hN6BKzx"
      "http_referrer" => "http://localhost:8000/admin/category/create"
      "parent_id" => "1"
      "name" => "asdasd"
      "slug" => "asdasd"
      "save_action" => "save_and_back"
    ]

Meaning that request does have name and slug attribute so I can not understand why I am getting this error.

Backpack, Laravel, PHP, DB version

When I run php artisan backpack:version the output is: 4.0, 7.9.2 , 7.3.1

1364 Field 'column' doesn't have a default value

In general ‘column’ doesn’t have a default value which means, you have created a column in the table without default value and not nullable also.

So, there are two solution for this problem, let’s discuss them one by one:

Eloquent Model

If you are sending the data to the server properly with this column and even then you are getting the error ‘column’ doesn’t have a default value. This means either you have missed the column by adding to your $fillable property in the related model or you have mentioned this column in the $guarded property of the model.

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

class Address extends Model
{
    use HasFactory;

    protected $fillable = [ ‘user_id’, ‘street’, ‘city’, ‘state’, ‘country’ ];
    protected $guarded = [];
}

You might know about the $fillable property, it allows columns to insert to the database, so if you have missed the column to add the $fillable property then you will definitely encounter this error.

Another thing is the $guarded property, this property of the model prevents the insertion to the database of the defined columns in the $guarded property.

So, either you have to remove the column from the $guarded property or add the column to the $fillable property as per your diagnosed issue.

Database migration

Yes, if the model is perfect as per the given information till now. But if you are missing the data in the form or want to make it an optional field then you can change the column to nullable or add default value to it via the database migration. Then you can refresh the database migration.

<?php

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

class CreateAddressTable extends Migration
{
    
    public function up()
    {
        Schema::create('addresses', function (Blueprint $table) {
            $table->id();
$table->foreignId('user_id');
            $table->string(‘city’);
            $table->string('state')->nullable();
            $table->string('country');
$table->string('street');
$table->tinyInteger(‘status’)->default(0);
            $table->timestamps();
        });
    }

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

In the above example, we have taken the “state” column and made it nullable. Now, state will be an optional field in the form. Similarly we can set the default value to it like we have set for status.

Hope you find this article useful, please comment below for any suggestion or issue with this information.

#1 10.10.2016 09:26:51

Невозможно добавить значение столбца при регистрации

Доброго времени суток!

Вот, в RegisterController, добавлено поле avatar:

protected function create(array $data) {
        return User::create([
                    'name' => $data['name'],
                    'email' => $data['email'],
                    'password' => bcrypt($data['password']),
                    'avatar' => 'assets/img/default/avatar.png', //аватар по умолчанию
        ]);
    }

И вот такая ошибка:

«SQLSTATE[HY000]: General error: 1364 Field ‘avatar’ doesn’t have a default value (SQL: insert into `users` (`name`, `email`, `password`, `updated_at`, `created_at`) …»

Никто не подскажет, что с этим можно сделать, или как обойти? Цель простая — заполнение поля значением по умолчанию.

Изменено Androbim (10.10.2016 09:27:39)

#3 10.10.2016 09:59:25

Re: Невозможно добавить значение столбца при регистрации

Большое спасибо!

#4 01.11.2016 09:41:32

Re: Невозможно добавить значение столбца при регистрации

А такой еще *ленивый* вопрос. Наверное, применять это имеет смысл только для тех полей, которые пользователь редактирует из фронтэнда? Ну, скажем, в админке этим занимаешься ты сам, и другим туда хода нет.

#5 01.11.2016 09:44:20

Re: Невозможно добавить значение столбца при регистрации

Что «это»? Массовое заполнение (Mass Assignment)?

#6 01.11.2016 11:51:34

Re: Невозможно добавить значение столбца при регистрации

Сорри, так точно. Помещать поля в $fillable.

#7 01.11.2016 12:28:51

Re: Невозможно добавить значение столбца при регистрации

Я везде использую массовое заполнение. ) Просто некоторые вещи нужно проверять перед тем, как записывать в базу на случай, если «хакеры» решат изменить какое-либо поле в своем профиле (установить флаг платной подписки, например).

Изменено AlexeyMezenin (01.11.2016 12:34:29)

#8 01.11.2016 12:34:56

Re: Невозможно добавить значение столбца при регистрации

Спасибо :-)

I am Facing the following error: SQLSTATE[HY000]: General error: 1364 Field ‘name’ doesn’t have a default value laravel 5.5. In This SolvdError Article, we’ll discuss How this error occurs and what are the possible fixes for this error. Let’s Solve this error together.

Contents

  1. What is SQLSTATE[HY000]: General error: 1364 Field ‘name’ doesn’t have a default value laravel 5.5 ?
  2. How To fix SQLSTATE[HY000]: General error: 1364 Field ‘name’ doesn’t have a default value laravel 5.5 error?
  3. Answer 1 : Edit your migration script
  4. Answer 2 : Remove «STRICT_ALL_TABLES or STRICT_TRANS_TABLES»
  5. Final Word
    • Also, Look at this solvderror

I am Facing the following error:

SQLSTATE[HY000]: General error: 1364 Field ‘name’ doesn’t have a default value laravel 5.5

How To fix SQLSTATE[HY000]: General error: 1364 Field ‘name’ doesn’t have a default value laravel 5.5 error?

  1. How To fix SQLSTATE[HY000]: General error: 1364 Field ‘name’ doesn’t have a default value laravel 5.5 error?

    To fix SQLSTATE[HY000]: General error: 1364 Field ‘name’ doesn’t have a default value laravel 5.5 error just Edit your migration script. To solve this error you should edit your migration script and put default value on this field. It will help you to remove this error. You can see this in the below example. $table->string('name')->nullable();

  2. SQLSTATE[HY000]: General error: 1364 Field ‘name’ doesn’t have a default value laravel 5.5

    To fix SQLSTATE[HY000]: General error: 1364 Field ‘name’ doesn’t have a default value laravel 5.5 error just Remove “STRICT_ALL_TABLES or STRICT_TRANS_TABLES”. First of all go to phpmyadmin. and then into variables. After doing this find “sql_mode” edit and remove “STRICT_ALL_TABLES or STRICT_TRANS_TABLES” By doing this you can solve your error completely. I hope this will help you.

Answer 1 : Edit your migration script

To solve this error you should edit your migration script and put default value on this field. It will help you to remove this error. You can see this in the below example.

$table->string('name')->nullable();

Answer 2 : Remove “STRICT_ALL_TABLES or STRICT_TRANS_TABLES”

First of all go to phpmyadmin. and then into variables.

After doing this find “sql_mode” edit and remove “STRICT_ALL_TABLES or STRICT_TRANS_TABLES”

By doing this you can solve your error completely. I hope this will help you.

Final Word

So This is All About this error You Just need to run a few commands and your error will be solved. Hope This Above Answer May helped to solve your warning. Comment Below which answer worked For You. Thank You.

Also, Look at this solvderror

  • Type ‘void’ is not assignable to type ((event: MouseEvent) => void) | undefined
  • TypeError: Cannot assign to read only property ‘0’ of object ‘[object Array]’
  • Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: require() of ES modules is not supported
  • JSON parse error: Cannot deserialize value of type `java.time.LocalDateTime` from String
  • Uncaught (in promise) TypeError: Failed to fetch and Cors error

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Laravel cors error
  • Laravel api response error
  • L2tp error 720
  • Laravel flash error
  • L2tp connection warning error code 809

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии