SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'patente' cannot be null (SQL: insert into cars (patente, marca, modelo, color, fecha_ingreso, updated_at, created_at) values (?, ?, ?, ?, ?, 2019-06-10 16:27:35, 2019-06-10 16:27:35)
Route::match(['get', 'post'], '/crear',[
'uses'=>'CarController#crear',
'as'=>'cars.crear'
]);
Short code to form
<div class="row">
<div class="col-md-6"></div>
<form action="{{route('cars.crear')}}" method="post">
#csrf
<div class="row form-group">
<div class="col-md-12">
<label for="true">Patente:</label>
<input type="text" name="patente" size="6" maxlength="6" class="form-control" required>
</div>
</div>
code create and show
public function crear(Request $request){
$patente=$request['patente'];
$marca=$request['marca'];
$modelo=$request['modelo'];
$color=$request['color'];
$fecha_ingreso=$request['fecha_ingreso'];
$car=new Car();
$car->patente=$patente;
$car->marca=$marca;
$car->modelo=$modelo;
$car->color=$color;
$car->fecha_ingreso=$fecha_ingreso;
$car->save();
return redirect()->back();
}
public function show(){
$cars=Car::all();
return view ('lista',['cars'=>$cars]);
}
CarController.php
public function crear(Request $request){
request()->validate([
'patente' => 'required',
'marca' => 'required',
'modelo' => 'required',
'color' => 'required',
'fecha_ingreso' => 'required',
'patente' => 'required',
'marca' => 'required',
'modelo' => 'required',
'color' => 'required',
'fecha_ingreso' => 'required'
]);
$car = Car::create([
patente => $request->patente,
marca => $request->marca,
modelo => $request->modelo,
color => $request->color,
fecha_ingreso => $request->fecha_ingreso
]);
return redirect()->back();
}
Your code looks fine, a bit verbose, so I cleaned it up a bit and added validation. The only other thing I can think to suggest is ensure your Car model has the fields added to the protected $fillable array.
Just Validate Your data before store it,
php artisan make:request ClearRequest
in App\Requests\ClearRequest,
class ClearRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'patente'=>'required',
'marca'=>'required',
'modelo'=>'required',
'color'=>'required',
'fecha_ingreso'=>'required',
'patente'=>'required',
'marca'=>'required',
'modelo'=>'required',
'color'=>'required',
'fecha_ingreso'=>'required'
];
}
}
in your controller
use App\Http\Requests\ClearRequest;
in your clear method
public function crear(ClearRequest $request){
...
}
in your view file sth like this,
<form action="/clear" method="POST">
#csrf
patente<br>
<input type="text" name="patente">
<br>
marca<br>
<input type="text" name="marca">
<br>
modelo<br>
<input type="text" name="modelo">
<br>
fecha_ingreso<br>
<input type="text" name="fecha_ingreso">
<br>
patente<br>
<input type="text" name="patente">
<br>
modelo<br>
<input type="text" name="modelo">
<br>
color<br>
<input type="text" name="color">
<br>
fecha_ingreso<br>
<input type="text" name="fecha_ingreso">
<br>
<input type="submit" value="Submit">
</form>
if it is helpful yor you upvote me :)
You are trying to store a null value in a NOT NULL column. Make sure you are passing patente correctly in the request.
Related
Route Code:
Route::group(['middleware' => 'auth', 'prefix' => 'admin'], function(){
Route::resource('gallery', GalleryController::class);
});
The Form I'm Using to Upload the File:
<form action="{{ route('gallery.store') }}" method="post" enctype="multipart/form-data">
#csrf
<div class="input-group mb-3">
<div class="custom-file">
<input type="file" class="custom-file-input" name="gallery_img" id="inputGroupFile01">
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>
</div>
</div>
#error('gal_img')
<span class="text-danger">{{ $message }}</span>
#enderror
<div class="input-group-append">
<div class="col-sm-10" style="padding-left: 1px;">
<button type="submit" class="btn btn-dark">Save</button>
</div>
</div>
Controller Code:
public function store(GalleryRequests $request)
{
$gal_img = $request->file('gallery_img');
$gal_file = date('YmdHi').$gal_img->getClientOriginalName();
$gal_img->move(public_path('upload/gallery'), $gal_file);
$save_path = 'upload/gallery/'.$gal_file;
Gallery::insert([
'gal_img' => $save_path
]);
$notification = array(
'message' => 'Slider Inserted Successfully',
'alert-type' => 'success'
);
return redirect()->back()->with($notification);
}
Request file validation:
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'gal_img' => 'required'
];
}
public function messages(){
return [
'gal_img.required' => 'Please Select an Image First',
];
}
The error I get when trying to save after selecting an Image:
Trying to figure out what I've done wrong for hours and am so frustrated right now, please help me to resolve this issue.
Thanks in advance.
Field in form is named gallery_img so that name has to be checked:
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'gallery_img' => 'required'
];
}
public function messages()
{
return [
'gallery_img.required' => 'Please Select an Image First',
];
}
Trying to write a function to create a new "profile" in my profiles table and get the following error:
"SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: profiles.about (SQL: insert into "profiles" ("dateofbirth", "state", "zipcode", "profilepic", "user_id", "updated_at", "created_at") values (2020-04-15, FL, 12345, /tmp/phpTT6CZr, 1, 2020-04-30 00:48:23, 2020-04-30 00:48:23))"
I've been reading answers to similar questions for the past few hours. Tried several different things, no luck so far. Hoping to see a solution that works in my code, and also get a better understanding of where exactly the error begins. The error message leads me to believe it's something to do with my "about" section in table. But unsure. I thought adding " protected $guarded = []; " to controller would solve but that gave the same result.
Here is what I'm working with:
Migration File:
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id'); //foreign key
$table->text('about')->nullable;
$table->text('profilepic')->nullable;
$table->date('dateofbirth')->nullable;
$table->unsignedinteger('zipcode')->nullable;
$table->string('state')->nullable;
$table->timestamps();
$table->index('user_id'); //index for foreign key
});
}
Profile Model:
class profile extends Model {
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
} }
I have also tried changing the profile model like below:
class profile extends Model {
public function user()
{
return $this->belongsTo(User::class);
}
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'dateofbirth' => 'datetime',
'zipcode' => 'unsignedinteger'
];
/*
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'about','profilepic','state', 'user_id', 'updated_at', 'created_at'
]; }
They both provide the same error message but with slightly different array values
Here is my controller store function:
public function store()
{
$data = request()->validate([
'dateofbirth' => 'required',
'state' => 'required',
'zipcode' => 'required',
'profilepic' => 'image'
]);
auth()->user()->profile()->create($data);
dd(request()->all());
}
Here is the view:
#extends('layouts.app')
#push('styles')
<link href="{{ asset('css/profile.css') }}" rel="stylesheet">
#endpush
#section('content')
{{-- This needs to present a create profile form --}}
<div class="row">
<h1 class="pl-4">CREATE YOUR PROFILE</h1>
</div>
<form action="/profile" class="pl-4" enctype="multipart/form-data" method="post">
#csrf
<div class="form-group row">
<label for="profilepic"
class="col-md-4 ocl-form-label"
>Upload a Profile Picture</label>
<input type="file"
class="form-control-file"
id="profilepic"
name="profilepic">
</div>
<div class="form-group">
<label for="about">Write your "About" Section here. What do you want us to know about you?</label>
<textarea type="text" class="form-control" id="about" name="about" rows="3"></textarea>
</div>
<div class="form-group">
<label for="dateofbirth">Date of Birth</label>
<input type="date"
id="dateofbirth"
name="dateofbirth">
</div>
<div class="form-group">
<label for="zipcode">Zipcode</label>
<input type="text" id="zipcode" name="zipcode">
</div>
<div class="form-group">
<label for="State">State</label>
<input type="text" id="state" name="state">
</div>
<div class="form-group row pt-4">
<button class="btn btn-primary">Submit</button>
</div>
</form> #endsection
That error means you're trying to set a foreign key column as null which is unacceptable, in this case, user_id on profiles table. Try to modify your code as such:
In your Profile model, add mass assignment columns:
protected $fillable = ['dateofbirth', 'state', 'zipcode', 'profilepic'];
In your controller store method:
//assuming the route method is authenticated such that there's always a logged in user
$user = auth()->user();
$data['user_id'] = $user->id;
$profile = Profile::create($data);
I'll add in also, I have since gotten this resolved with implementing #djunehor's answer. But one thing that helped get the problem resolved was adding in this to the controller:
public function store(Request $request)
At first I was not passing the request in and saving it to a variable like this, but this step seems to have made a big difference for the errors I was running into.
At first I was just doing this:
public function store()
I have 4 fields which are id, name, prenom, date_naissance.
When I insert a recording in my phymyadmin, I don't have a problem with the date_naissance.
However, when I try to insert a date_naissance in my insert form, I have an error message.
SQLSTATE[HY000]: General error: 1364 Field 'date_naissance' doesn't
have a default value (SQL: insert into eleves (nom, prenom,
updated_at, created_at) values (Benoit, Piret, 2019-03-07
22:31:24, 2019-03-07 22:31:24))
Do you see the problem ?
public function create()
{
return view('admin.eleves.create', compact('eleves'));
}
public function store(Request $request)
{
$request->validate([
'nom' => 'required|string',
'prenom' => 'required|string',
'date_naissance' => 'required|date'
]);
Eleve::create($request->all());
return redirect()->route('eleves.index')
->with('success', 'save');
}
My View create
<form class="panel-body" action="{{route('eleves.store')}}" method="POST">
#csrf
<fieldset class="form-group">
<label for="form-group-input-1">Nom</label>
<input type="text" name="nom" class="form-control" id="form-group-input-1">
</fieldset>
<fieldset class="form-group">
<label for="form-group-input-1">Prénom</label>
<input type="text" name="prenom" class="form-control" id="form-group-input-1">
</fieldset>
<fieldset class="form-group">
<label for="form-group-input-1">Date naissance</label>
<input type="date" name="date_naissance" class="form-control" id="form-group-input-1">
</fieldset>
Back
<button type="submit" class="btn btn-sm btn-primary">Valider</button>
</form>
Model:
class Eleve extends Model
{
//
protected $fillable = ['nom', 'prenom'];
protected $dates = ['date_naissance'];
In your Model
class Eleve extends Model
{
//
protected $fillable = ['nom', 'prenom','date_naissance']; // missing date_naissance here.
protected $dates = ['date_naissance'];
You will need to specify either a fillable or guarded attribute on the model, as all Eloquent models protect against mass-assignment by default.
Fillable you specify which fields are mass-assignable in your model, you can do it by adding the special variable $fillable to the model. So in the model you need to add also date_naissance:
class Eleve extends Model {
protected $fillable = ['nom', 'prenom','date_naissance']; //only the field names inside the array can be mass-assign
protected $dates = ['date_naissance'];
}
More details: you can easily understand here What does “Mass Assignment” mean in Laravel
I am trying to work on a Laravel PHP project and as I am new to this framework. First step I had to do is build a Registration Form. However, when I click on the Submit button no error is given, and nothing is registered in my users table.
Here is the code for my project so far :
My users migration table up and down functions
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->boolean('sexe');
$table->integer('age');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
I added to the original two fields which are : "sexe a boolean F/M" and age
My RegisterController important functions
<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Mail;
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = '/register';
public function __construct()
{
$this->middleware('guest');
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required', 'string', 'max:255',
'sexe'=> 'required|in:male,female',
'age' => 'required|integer|max:100',
'email' => 'required', 'string', 'email', 'max:255', 'unique:users',
'password' => 'required', 'string', 'min:5', 'confirmed',
]);
}
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'sexe' => $data['sexe'],
'age' => $data['age'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
/**
* Override default register method from RegistersUsers trait
*
* #param array $request
* #return redirect to $redirectTo
*/
public function register(Request $request)
{
$this->validator($request->all())->validate();
//add activation_key to the $request array
$activation_key = $this->getToken();
$request->request->add(['activation_key' => $activation_key]);
$user = $this->create($request->all());
//$this->guard()->login($user);
//write a code for send email to a user with activation link
$data = array('name' => $request['name'], 'email' => $request['email'], 'activation_link' => url('/activation/' . $activation_key));
Mail::send('emails.mail', $data, function($message) use ($data) {
$message->to($data['email'])
->subject('Activate Your Account');
$message->from('s.sajid#artisansweb.net');
});
return $this->registered($request, $user)
?: redirect($this->redirectPath())->with('success', 'We have sent an activation link on your email id. Please verify your account.');
print_r($request->input());
}
}
My Routes
Route::auth();
Route::get('/home', 'HomeController#index');
Auth::routes();
Route::get('/register', 'RegisterController#create');
Route::post('/register', 'RegisterController#register');
Route::get('/', function () {
return view('welcome');
});
My User.php Model fillable
protected $fillable = [
'name','sexe','age','email','password',
];
protected $hidden = [
'password', 'remember_token',
];
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
}
My blade file register part (register.blade.php)
<body>
<form method="POST" role="form" action="//IJJI/resources/views/chat.blade.php">
<meta name="csrf-token" content="{{ csrf_token() }}">
<input id="name" name="name"type="text" class="form-control" placeholder="Entrez ici votre Pseudo *" value="" />
<label class="radio inline">
<input id="homme" type="radio" name="sexe" value="homme" checked>
<span> Homme </span>
</label>
<label class="radio inline">
<input id="femme" type="radio" name="sexe" value="femme">
<span>Femme </span>
</label>
<input id="age" name="age" type="integer" class="form-control" placeholder="Saisissez votre age *" value="" />
<input id="Email" name="email" type="email" class="form-control" placeholder="Saisissez votre Email *" value="" />
<input id="password" name="password" type="password" class="form-control" placeholder="Entrez votre Mot de Passe *" value="" />
<input id="confirmpassword" name="confirmpassword" type="password" class="form-control" placeholder="Confrimez votre Mot de Passe *" value="" />
<button type="submit" class="btnRegister">
Je deviens membre Gratuitement
</button>
</form>
</body>
I have done PHP artisan make auth generated the files, made .env file adequate to my MySQL database with the username and password, even checked the PhpMyAdmin configuration, but all in vain.
After 4 days of search in Google websites I can't figure out where I am wrong.
P.S : Another thing that could be wrong is that code like this :
#section
#endsection
never gets accepted and just shows like normal text on my browser.
Thanks a lot for your help
Check your laravel logs location: storage/logs you will get errors.
i have notice you are using $table->boolean('sexe') and in validation you are giving string boolen should be 0/1
'sexe'=> 'required:in:true,false',
also change in your html form to 0,1 currently you are using male, female
Are you getting error?
Besides, can you please the following line at the top of your form to see if there is any validation error or not. After that try submitting the form and see if there is any error or not!
#if(count($errors) > 0)
<div style="color:red">
#foreach ($errors->all() as $message)
<ul>
<li>{{$message}}</li>
</ul>
#endforeach
</div>
#endif
And remove the action form the form tags.
Use:
#csrf
or
{{csrf_field()}}
instead of
<meta name="csrf-token" content="{{ csrf_token() }}">
Here is my content.blade.php
<form action="{{ route('home') }}" method="post">
<input class="input-text" type="text" name="name" value="Your Name *" onFocus="if(this.value==this.defaultValue)this.value='';" onBlur="if(this.value=='')this.value=this.defaultValue;">
<input class="input-text" type="text" name="email" value="Your E-mail *" onFocus="if(this.value==this.defaultValue)this.value='';" onBlur="if(this.value=='')this.value=this.defaultValue;">
<textarea name="text" class="input-text text-area" cols="0" rows="0" onFocus="if(this.value==this.defaultValue)this.value='';" onBlur="if(this.value=='')this.value=this.defaultValue;">Your Message *</textarea>
<input class="input-btn" type="submit" value="send message">
{{ csrf_field() }}
</form>
That's my routes(web.php)
Route::group(['middleware'=>'web'], function(){
Route::match(['get', 'post'], '/', ['uses'=>'IndexController#execute', 'as'=>'home']);
Route::get('/page/{alias}', ['uses'=>'PageController#execute', 'as'=>'page']);
Route::auth();
});
And Finally here is my IndexController.php, method execute():
if($request->isMethod('post')){
$messages = [
'required' => "Поле :attribute обязательно к заполнению",
'email' => "Поле :attribute должно соответствовать email адресу"
];
$this->validate($request, [
'name' => 'required|max:255',
'email' => 'required|email',
'text' => 'required'
], $messages);
dump($request);
}
So, the problem is that dump($request) does not work, and I also tried to comment everything except dump($request), and the result is the same. I think it just skips if($request->isMethod('post')) so that it returns that the method is not true, may be there is something wrong with token, I am not sure.
How to resolve this issue?
edit:
That's the code above if statement
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Page;
use App\Service;
use App\Portfolio;
use App\People;
use DB;
class IndexController extends Controller
{
//
public function execute(Request $request){
You should assign $request to somewhere first.
For example, if i have a store method and i have to use Request $request for grabbing the information, i should establish it first, so by establishing it my application will recognize what does the variable is retrieving, let me show you an example code:
public function store(Request $request)
{
$data = $request->all();
$data['a'] = Input::get('a');
$data['b'] = Input::get('b');
$data['c'] = Input::get('c');
$data['d'] = Input::get('d');
$data['e'] = Input::get('e');
Letters::create($data);
return redirect::to('/');
}
Did you get it?
If not, here is an example with isMethod:
$method = $request->method();
if ($request->isMethod('post')) {
//
}
In your code i did not see the $var = $request->method(); (or what you want it to be).