You need to send the user_id also when submitting the form
Can't save information to database via a form in laravel:SQLSTATE[23000]:error
I am really confused. I'm a beginner in laravel 8 and I'm working on a pet registration platform. I want the User to collect his/her pet's info through a form, but when I click on the submit button to save the info to the database, nothing seems to happen(meaning no error). And when I use the tinker command >>> Pet::all();, nothing gets save to the database. I also tried saving the info manually through tinker, but then I get this error: >>> $pet->save(); Illuminate/Database/QueryException with message 'SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: pets.user_id (SQL: insert into "pets" ("nickname", "species", "date_of_birth", "gender", "color", "description", "updated_at", "created_at") values (Tom, Domestic cat, 2012-11-10, male, blue, description, 2020-12-20 05:00:49, 2020-12-20 05:00:49))'
This is the PetsController:
<?php
namespace App\Http\Controllers;
use App\Models\Pet;
use App\Models\User;
class PetsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function create()
{
return view('create');
}
public function store()
{
$data = request()->validate([
'nickname' => 'required',
'species' => 'required',
'date_of_birth' => 'required',
'gender' => 'required',
'color' => 'required',
'description' => 'required',
]);
auth()->user()->pets()->create([
'nickname' => $data['nickname'],
'species' => $data['species'],
'date_of_birth' => $data['date_of_birth'],
'gender' => $data['gender'],
'color' => $data['color'],
'description' => $data['description'],
]);
return redirect('/');
}
}
This is the Model for User:
<?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;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'username',
'phone',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function pets()
{
return $this->hasMany(Pet::class);
}
This is model for Pet:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Pet extends Model
{
protected $guarded= [];
public function user()
{
return $this->belongsTo(User::class);
}
}
This is the form view:
@extends('layouts.app')
@section('content')
<div class="container py-5">
<form action="/register" method="post">
@csrf
<div class="row">
<div class="col-10">
<div class="row justify-content-center">
<h1><strong>Add A Pet</strong></h1>
</div>
<div class="form-group row py-4">
<label for="nickname" class="col-md-4 col-form-label text-md-right">Nickname</label>
<div class="col-md-6">
<input id="nickname" type="text" class="form-control @error('nickname') is-invalid @enderror"
name="nickname"
value="{{ old('nickname') }}"
placeholder="Enter the name of the animal"
required autocomplete="nickname" autofocus>
@error('nickname')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="form-group row">
<label for="species" class="col-md-4 col-form-label text-md-right">Species</label>
<div class="col-md-6">
<select id="species" class="form-control @error('species') is-invalid @enderror"
name="species"
value="{{ old('species') }}"
required autocomplete="species" autofocus>
<option disabled selected>Select species</option>
<option>Dog</option>
<option>Domestic cat</option>
<option>other</option>
</select>
@error('species')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="form-group row py-4">
<label for="date_of_birth" class="col-md-4 col-form-label text-md-right">Date of birth</label>
<div class="col-md-6">
<input id="date_of_birth" type="date" class="form-control @error('date_of_birth') is-invalid @enderror"
name="date_of_birth"
value="{{ old('date_of_birth') }}"
placeholder="yyyy-mm-dd"
required autocomplete="date_of_birth" autofocus>
@error('date_of_birth')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="form-group row justify-content-center" style="padding-left:108px">
<div class="form-group col-md-3">
<label for="gender">Gender</label>
<select id="species" class="form-control @error('species') is-invalid @enderror"
name="species"
value="{{ old('species') }}"
required autocomplete="species" autofocus>
<option>Unknown</option>
<option>Male</option>
<option>Female</option>
</select>
@error('species')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
<div class="form-group col-md-3">
<label for="color">Color</label>
<input id="color" type="text" class="form-control @error('color') is-invalid @enderror"
name="color"
value="{{ old('color') }}"
placeholder="Select color"
required autocomplete="color" autofocus>
@error('color')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="form-group row py-4">
<label for="description" class="col-md-4 col-form-label text-md-right">Description</label>
<div class="col-md-6">
<textarea name="description" id="description" rows="3"
class="form-control @error('description') is-invalid @enderror"
value="{{ old('description') }}"
placeholder="Enter a description of the animal"></textarea>
@error('description')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="row col-md-6" style="margin-left:300px">
<button class="btn btn-primary btn-lg btn-block">Finish</button>
</div>
<div class="row col-md-6 py-4" style="margin-left:430px">
<a href="#"><u><h4>Add Pet Later</h4></u></a>
</div>
</div>
</div>
</form>
</div>
@endsection
This is the Routes file:
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/register/create', [App\Http\Controllers\PetsController::class, 'create']);
Route::post('/register', [App\Http\Controllers\PetsController::class, 'store']);
Route::get('/profile/{user}', [App\Http\Controllers\ProfilesController::class, 'index'])->name('profile.show');
And finally the migrations for pets table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePetsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('pets', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('nickname');
$table->string('species');
$table->date('date_of_birth');
$table->string('gender');
$table->string('color')->nullable();
$table->text('description')->nullable();
$table->timestamps();
$table->index('user_id');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('pets');
}
}
I'm confused and I've been struggling for quite a while now!
And what has changed since you were just getting back to the create page, without errors, to start getting this current error?
I see you have this at your controller:
public function __construct()
{
$this->middleware('auth');
}
So I assume you are logged in otherwise you shouldn't be having the chance to submit that form at all...
Please or to participate in this conversation.