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
Related
I'm working on Laravel project and i would like to know:
how to insert data to my multiple related tables ?
How can we insert author id in the author_type_id field of the Author table?
How to store author_id in post?
So idon't know how to insert related models using a form. thanks for your help :)
my models
//Post model
class Post extends Model
{
//
protected $fillable = [
'post_type_id','author_id','author_type_id','article'
];
public function posttype()
{
return $this->belongsTo(Posttype::class);
}
public function author()
{
return $this->belongsTo(Author::class);
}
public function authortype()
{
return $this->belongsTo(Authortype::class);
}
}
//Posttype model
class Posttype extends Model
{
//
protected $fillable = [
'post_type'
];
public function posts()
{
return $this->hasMany(Post::class);
}
}
//author model
class Author extends Model
{
//
protected $fillable = [
'author_name','author_first_name','author_type_id'
];
public function posts()
{
return $this->belongsToMany(Post::class);
}
public function authortype()
{
return $this->belongsTo(Authortype::class);
}
}
//Authortype model
class Authortype extends Model
{
//
protected $fillable = [
'author_type '
];
public function author()
{
return $this->hasMany(Author::class);
}
public function posts()
{
return $this->hasMany(Post::class);
}
}
// PostsController Contoller
class PostsController extends Controller
{
public function index()
{
return view('index')->with('posts',Post::all());
}
public function create()
{
return view('create')->with('posttypes',$posttypes)
->with('authors',$authors)
->with('authortypes',$authortypes);
}
public function store(Request $request)
{
$this->validate($request,[
"post_type_id" => "required",
"author_id" => "required",
"author_type_id" => "required",
"article" => "required"
]);
//How can we insert author id in the author_type_id field of the Author table?
$post = Post::create([
"post_type_id" => $request->post_type_id,
"author_id" => $request->author_id,
"author_type_id" => $request->author_type_id,
"article" => $request->article,
]);
return redirect()->back();
}
}
//create post blade
#section('content')
<div class="container">
<form action="{{route('store')}}" method="POST" enctype="multipart/form-data">
{{ csrf_field()}}
<div class="form-group">
<label for="posttype">Post Type</label>
<select class="form-control" id="posttype" name="post_type_id">
#foreach ($posttypes as $posttype)
<option value="{{$posttype->id}}">{{$posttype->post_type}}</option>
#endforeach
</select>
</div>
//author type for author model (author_type_id)
<div class="form-group">
<label for="authortype">Author Type</label>
<select class="form-control" id="authortype" name="author_type_id">
#foreach ($authortypes as $authortype)
<option value="{{$authortype->id}}">{{$authortype->author_type}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="author_name">Author Name</label>
<input type="text" class="form-control" name="author_name" placeholder="your name">
</div>
<div class="form-group">
<label for="author_first_name">Author First Name</label>
<input type="text" class="form-control" name="author_first_name" placeholder="your first name">
</div>
//How to store author_id in post
<div class="form-group">
<label for="content">article</label>
<textarea class="form-control" name="article" rows="8" cols="8"></textarea>
</div>
<button type="submit" class="btn btn-primary">{{__('main.save')}}</button>
</form>
</div>
#endsection
I found solution, May this can help you in future.
$author = Author::create([
'author_type_id' => $request->author_id,
]);
$post = Post::create([
"post_type_id" => $request->post_type_id,
"author_id" => $author->id,
"author_type_id" => $request->author_type_id,
"article" => $request->article,
]);
Auther::create([
'author_type_id' => $request->author_id,
]);
i am a begineer of codeigniter 4.i had a problem is Record is not added in to the database. i got the url link like this http://localhost:8080/index.php/usersCreate error said Whoops!
We seem to have hit a snag. Please try again later... . i don't know how to solve problem what i tried so far i attached below.
View
User.php
<form method="post" id="add_create" name="add_create" action="<?php echo site_url('usersCreate');?>">
<div class="form-group col-md-6">
<label>First Name</label>
<input type="text" name="empid" class="form-control" id="fname" placeholder="fname">
</div>
<div class="form-group col-md-6">
<label>Last Name</label>
<input type="text" name="lname" class="form-control" id="lname" placeholder="lname">
</div>
<div class="form-group col-md-6" align="center">
<Button class="btn btn-success" style="width: 80px;">Submit</Button>
</div>
</form>
Controller
User.php
public function index()
{
return view('User');
}
// insert data
public function store() {
$userModel = new UserModel();
$data = [
'fname' => $this->request->getVar('fname'),
'lname' => $this->request->getVar('lname'),
];
$userModel->insert($data);
return $this->response->redirect(site_url('users'));
}
UserModel
<?php
namespace App\Models;
class UserModel extends Model
{
protected $table = 'records';
protected $primaryKey = 'id';
protected $allowedFields = ['fname', 'lname'];
}
Routes
$routes->get('/', 'User::index');
$routes->post('usersCreate', 'User::store');
I don't know CodeIgniter per se, but you should figure out how to get more meaningful data. Is your environment set to development environment? Usually you will get more info than Whoops! We seem to have hit a snag. Please try again later... and get more details on the error.
But I see you're trying to go to the page, where you add a user. There's 2 ways to methods to reach that page, GET (this is when you just go to the page as usual) and POST (this is when you submit the form).
But the request data will only be available if you submit the form. Thus you have to differentiate between the 2 methods. In your Controller you need to do something like
if ($this->request->getMethod() === 'post') { ... }
which is when you submit the form.
Check out https://codeigniter.com/user_guide/tutorial/create_news_items.html which should have more info. Snippet
public function create()
{
$model = new NewsModel();
if ($this->request->getMethod() === 'post' && $this->validate([
'title' => 'required|min_length[3]|max_length[255]',
'body' => 'required'
]))
{
$model->save([
'title' => $this->request->getPost('title'),
'slug' => url_title($this->request->getPost('title'), '-', TRUE),
'body' => $this->request->getPost('body'),
]);
echo view('news/success');
}
else
{
echo view('templates/header', ['title' => 'Create a news item']);
echo view('news/create');
echo view('templates/footer');
}
}
I normally use a short method to get data and then submit it to the database. Here is what id do. check this. I am just updating your code
// insert data
public function store() {
$userModel = new \App\Models\UserModel();
$data = [
'fname' => $this->request->getPost('fname'),
'lname' => $this->request->getPost('lname'),
];
$userModel->insert($data);
return redirect()->to(site_url('users'));
}
then check you html file you are missing the firstname name
Try this one
<form method="post" id="add_create" action="<?php echo site_url('usersCreate');?>">
<div class="form-group col-md-6">
<label>First Name</label>
<input type="text" name="fname" class="form-control" id="fname" placeholder="fname">
</div>
<div class="form-group col-md-6">
<label>Last Name</label>
<input type="text" name="lname" class="form-control" id="lname" placeholder="lname">
</div>
<div class="form-group col-md-6" align="center">
<button type="submit" class="btn btn-success" style="width: 80px;">Submit</button>
</div>
</form>
For the check your model i think is not configured well check this one
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
protected $returnType = 'object';
protected $useSoftDeletes = false;
protected $allowedFields = ['fname', 'lname', 'email']; // did you add this side of the site model
protected $useTimestamps = false;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
protected $validationRules = [];
protected $validationMessages = [];
protected $skipValidation = false;
}
Check my code if it did not help you call my attentions okay. I am still ready to help
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 would like to learn to create a dropdown list with a foreign key on Laravel.
For information, I have a table named series with 3 fields id, name, fk_mark.
Then, I have another table named marks with 2 fields id, name_mark.
My create works correctly, here is the proof.
I am stuck about the dropdownlist, what is the syntax please for my foreign key ?
<fieldset class="form-group">
<label for="form-group-input-1">Name serie</label>
<input type="text" name="name" class="form-control" id="form-group-input-1">
</fieldset>
<fieldset class="form-group">
<label for="form-group-input-1">FK Mark</label>
<input type="text" name="fk_mark" class="form-control" id="form-group-input-1">
</fieldset>
I have tried this but without result...
<div class="form-group">
<label for="company-content">Select compagny</label>
<select name="fk_mark" class="form-control">
#foreach($series as $serie)
<option value="{{$serie->id}}"> {{$serie->name}} </option>
#endforeach
</select>
</div>
Here is my Models
Model Mark
class Mark extends Model
{
protected $fillable = ['name_mark'];
public function series(){
return $this->hasMany('App\Serie', 'fk_mark');
}
}
Model Serie
class Serie extends Model
{
protected $fillable = ['name', 'fk_mark'];
public function marks(){
return $this->belongsTo('App\Mark', 'fk_mark');
}
}
SerieController
public function index()
{
$series = Serie::oldest()->paginate(5);
return view('admin.series.index', compact('series'))
->with('i', (request()->input('page', 1)-1)*5);
}
public function create()
{
return view('admin.series.create');
}
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'fk_mark' => 'required'
]);
Serie::create($request->all());
return redirect()->route('series.index')
->with('success', 'save');
}
Thank you very much for your help.
As many know, Laravel automatically creates the User model when you create a project. I then created an auth interface php artisan make:auth. The auto generated register method was working normaly. I then added a not null column to the migration for the user table. Now it isn't working anymore. I don't know where exactly the insert happens when laravel creates this auth scaffolding. I tried editing the create method in RegisterController but it didn't worked.
class RegisterController extends Controller
{
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'tipo' => $data['tipo'], // name of the new column I added
'password' => bcrypt($data['password']),
]);
}
}
On the register <form> I added the input field tipo. The generated code includes:
<form class="form-horizontal" method="POST" action="{{ route('register') }}">
<input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" required autofocus>
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required>
<select id="tipo" class="form-control" name="tipo" value="{{ old('tipo') }}" required>
<option value="1">Gerente</option>
<option value="2">Caixa</option>
<option value="3">Garçom</option>
</select>
<input id="password" type="password" class="form-control" name="password" required>
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>
<button type="submit" class="btn btn-primary">
Registrar
</button>
In the User class model, I added the new column to the fillable:
/protected $fillable = [
'name', 'email', 'password', 'tipo',
];
On the routes, web.php only Auth::routes();. If I run php artisan route:list it shows me that for the POST method the uri register leads to RegisterController#register but on the RegisterController it has only the create method I posted and validator method. So, where the registration is actually happening? In terms of laravel, where it runs the $user->save() method?
Edit: All I want to do is modify it so it include the new <input> for the new column
Edit 2: I found out that actually the code is not reaching the create method because I added dd($data) before the return and still the same behavior, then I added some forced syntax error and also the same thing happened.
Firstly, Add the recently added column to $fillable array in the app\User.php file.
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/protected $fillable = [
'name', 'email', 'password', 'tipo'
];