SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'score' cannot be null - laravel

Controller
public function getScore(Request $request, $id)
{
// $scores = Criteria::find($id);
$contestants = Contestant::find($id);
foreach ($request->criteria as $id => $criteria){
$criteriaModel = Score::find($id);
$scores = new Score();
$scores->judge_name = $request->input('judge_name');
$scores->contestant = $contestants->name;
$scores->criteria = $criteriaModel->criteria;
$scores->score = $scores->score;
$scores->save();
}
return redirect('/tabulation')->with('status', 'Score saved!');
}
Blade
#foreach ($criterias as $criteria)
<div class="form-group col-md-6">
<label for="{{$criteria->name}}">{{$criteria->name}} </br> (0 - {{$criteria->points}})</label>
<input type="text" name="criteria[{{$criteria->id}}][criteria]" value="{{$criteria->name}}" hidden>
<input type="text" name="score[{{$criteria->id}}][score]" class="form-control" placeholder="Input score" required>
</div>
#endforeach

Form field names can contain brackets to store multiple properties for a single name:
#foreach ($criterias as $criteria)
<div class="form-group col-md-6">
<label for="{{$criteria->name}}">{{$criteria->name}} </br> (0 - {{$criteria->points}})</label>
<input type="text" name="criterias[{{$criteria->id}}][name]" value="{{$criteria->name}}" hidden>
<input type="text" name="criterias[{{$criteria->id}}][points]" class="form-control" placeholder="Input score" max="{{$criteria->points}}" name="score" required>
</div>
#endforeach
The above form would result the $request->criterias variable containing the following value:
array:2 [▼
1 => array:2 [▼
"name" => "test"
"points" => "dd"
]
2 => array:2 [▼
"name" => "tes22t"
"points" => "sdsd"
]
]
This value can be used in the controller for creating multiple scores:
foreach ($request->criterias as $id => $criteria){
$criteriaModel = Criteria::find($id);
$scores = new Score();
$scores->judge_name = $request->input('judge_name');
$scores->contestant = $contestants->name;
$scores->criteria = $criteriaModel->name;
$scores->score = $criteria->points;
$scores->save();
}

First of all you have to change the name of your input to be an array like so:
<input type="text" name="criteria[]" value="{{$criterias->name}}" hidden>
and in your controller you have to loop through the inputs:
foreach ($request->input('criteria') as $criteria){
$scores = new Score();
$scores->judge_name = $request->input('judge_name');
$scores->contestant = $contestants->name;
$scores->criteria = $request->input('criteria');
$scores->score = $request->input('score');
$scores->save();
}

Related

Attempt to read property "name" on array (Select with Livewire)

I'm trying to make a dependent select with Livewire.
My problem is that when I load the second select, it loads it without problems, but when I select an option from the second select, it throws me this error.
Attempt to read property "nombre" on array
select template
<div class="container">
<div class="row mb-3">
<div class="col-4">
<label class="form-label">Tipo de Inscripcion</label>
<select wire:model="selectedTipoInscripcion" class="form-select">
<option selected>Seleccionar ...</option>
#foreach($tipoInscripcion as $tipo)
<option value="{{ $tipo -> id }}">{{ $tipo -> nombre}}</option>
#endforeach()
</select>
</div>
#if(!is_null($tipoPrograma))
<div class="col-4">
<label class="form-label">Tipo de Programa</label>
<select wire:model="selectedTipoPrograma" class="form-select">
<option selected>Seleccionar ...</option>
#foreach($tipoPrograma as $tipo)
<option value="{{ $tipo -> id}}">{{ $tipo -> nombre}}</option>
#endforeach()
</select>
</div>
#endif
</div>
</div>
The problem is in
<option value="{{ $tipo -> id}}">{{ $tipo -> nombre}}</option>
My Component
<?php
namespace App\Http\Livewire;
use App\Models\Curso;
use App\Models\Programa;
use Livewire\Component;
class SelectAnidado extends Component
{
public $selectedTipoInscripcion = null, $selectedTipoPrograma = null, $SelectedProgrCur = null;
public $tipoPrograma = null, $progrCur = null, $sw = null;
public function render()
{
$programa = (object) ['id' => 1, 'nombre' => 'Programa'];
$curso = (object) ['id' => 2, 'nombre' => 'Curso'];
$ti = collect([$programa, $curso]);
return view('livewire.select-anidado', [
'tipoInscripcion' => $ti
]);
}
public function updatedselectedTipoInscripcion($id)
{
if ($id == 1) {
$doctorado = (object) ['id' => 1, 'nombre' => 'doctorado'];
$maestria = (object) ['id' => 2, 'nombre' => 'maestria'];
$especialidad = (object) ['id' => 3, 'nombre' => 'especialidad'];
$diplomado = (object) ['id' => 4, 'nombre' => 'diplomado'];
$this->tipoPrograma = collect([$doctorado, $maestria, $especialidad, $diplomado]);
}
}
}
It tells me that I am trying to access an array as if it were an object.
But then the error should also appear when the is loaded.
Why does it only appear when I make the selection?
I think problem is here :
$this->tipoPrograma = collect([$doctorado, $maestria, $especialidad, $diplomado]);
you're passing array in tipoPrograma, and each variables is array too.

Livewire checkboxes selected by default

What I would like :
By default check all checkboxes
Get the value sheet id for later
First issue :
Is it possible to sort / order them by id ?
Because for the moment it orders them by the order of check.
screenshot 2
If someone can help me I would be glad thanks :D
Here is my view :
#foreach($sheets as $sheet)
<div class="inputGroup">
<input id="{{$loop->index}}" wire:model="selectedBoxes" type="checkbox" value="{{$loop->index}}" checked/>
<label for="{{$loop->index}}">Feuille {{$loop->index+1}}: {{$sheet}}</label>
</div>
#endforeach
Here are the results when I dd($sheets) :
^ array:4 [▼
0 => "All ValueRAM FURY"
1 => "Non-ECC ValueRAM"
2 => "All FURY"
3 => "KSM (Server Premier)"
]
Here is my component :
public $sheets = [];
public $selectedBoxes = [];
...
public function readExcel()
{
...
$data = [];
// Return an import object for every sheet
foreach($import->getSheetNames() as $index => $sheetName)
{
$data = $import->getSheetNames();
$this->sheets = $data;
}
}
Website view :
screenshot 1
welcome to StackOverflow! You could remove the checked tag from your select and let wire:model do it's thing:
public $sheets = [
0 => "All ValueRAM FURY",
1 => "Non-ECC ValueRAM",
2 => "All FURY",
3 => "KSM (Server Premier)"
];
// wire:model will ensure that all are checked by default.
public $selectedBoxes = [true, true, true, true];
and in your view:
(Take a look at the wire:model property and the checked attribute is gone)
#foreach($sheets as $sheet)
<div class="inputGroup">
<input id="sheet-{{$loop->index}}"
wire:model="selectedBoxes.{{ $loop->index }}"
type="checkbox"
value="{{$loop->index}}" />
<label for="sheet-{{$loop->index}}">Feuille {{$loop->index+1}}: {{$sheet}}</label>
</div>
#endforeach
Thanks to Laisender I finded what I wanted.
What changed in my component :
public $counter = 0;
...
foreach($import->getSheetNames() as $index => $sheetName)
{
$data = $import->getSheetNames();
$this->sheets = $data;
array_push($this->selectedBoxes, "$this->counter");
$this->counter += 1;
}
My view :
#foreach($sheets as $sheet)
<div class="inputGroup">
<input id="sheet-{{$loop->index}}" wire:model="selectedBoxes.{{$loop->index}}" type="checkbox" value="{{$loop->index}}"/>
<label for="sheet-{{$loop->index}}">Feuille {{$loop->index+1}}: {{$sheet}}</label>
</div>
#endforeach

Laravel insert multiple records in pivot table from arrays

I'm trying to save multiple records(rows) in a table. The html fields are dynamic fields and declared as array, so they can be 1, 2 or more.
My blade:
<div class="col-md-12" id="inputFormRow" style="padding-left: 0px;">
<div class="input-group mb-3">
<input type="text" name="tableName[]" class="form-control m-input" placeholder="Name" autocomplete="off">
<input type="text" name="fromNr[]" class="form-control m-input" placeholder="From" autocomplete="off">
<input type="text" name="toNr[]" class="form-control m-input" placeholder="to" autocomplete="off">
<div class="input-group-append">
<button id="removeRow" type="button" class="btn btn-danger">X</button>
</div>
</div>
+
My JS to create dynamic fields:
$("#addRow").click(function () {
var html = '';
html += '<div class="col-md-12" id="inputFormRow" style="padding-left: 0px;">';
html += '<div class="input-group mb-3">';
html += '<input type="text" name="tableName[]" class="form-control m-input" placeholder="Name" autocomplete="off">';
html += '<input type="text" name="fromNr[]" class="form-control m-input" laceholder="From" autocomplete="off">';
html += '<input type="text" name="toNr[]" class="form-control m-input" placeholder="To" autocomplete="off">';
html += '<div class="input-group-append">';
html += '<button id="removeRow" type="button" class="btn btn-danger">X</button>';
html += '</div>';
html += '</div>';
$('#newRow').append(html);
});
My Offer.php Model:
protected $fillable = ['some columns];
public function table()
{
return $this->hasMany(Table::class);
}
My Table.php Model:
protected $fillable = ['offer_id','tableName','fromNr','toNr'];
public function offer()
{
return $this->hasMany(Offer::class);
}
Now, in my Controller, I have to get request input values and then save into Table table. The input values can be more than 1 and dynamically.
My tries:
public function store(Request $request)
{
$statement = DB::select("SHOW TABLE STATUS LIKE 'offer'");
$nextId = $statement[0]->Auto_increment;
$tableName = $request->get('tableName');
$fromNr = $request->get('fromNr');
$toNr = $request->get('toNr');
$offer = Offer::find($nextId);
$offer->table()->saveMany([
new Table(['restaurant_offer_id' => $nextId]),
new Table(['tableName' => $tableName]),
new Table(['fromNr' => $fromNr]),
new Table(['toNr' => $toNr]),
]);
}
Thank you in Advance.
If you want to make it dynamic you have to loop over the input array.
$tables = [];
foreach($tableName as $key => $value) {
$table = new Table;
$table->tableName = $tableName[$key];
$table->fromNr = $fromNr[$key];
$table->toNr = $toNr[$key];
$tables[] = $table;
}
$offer->table()->saveMany($tables);
If you use name="example[]" on the view, you are receiving the variable as an array in the controller. Also if you use Eloquent Model binding you can save the model instance to the database with simpler syntax.
Try something like this in the controller:
public function store(Request $request)
{
foreach($request->tableName as $key => $tableName)
{
Offer::create(['tableName' => $tableName',
'fromNr' => $request->fromNr[$key],
'toNr' => $request->toNr[$key]])
}
}
Additionally I recommend to use plural naming in case of arrays. Like tableNames, fromNrs. So you know that it should contain multiple variables.

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'player_id' cannot be null

I have this error when I try to add data. I have 2 tables on my database, the (players) table and the (stats) table which are connected with the "player_id" being the foreign key to the players table.
players table:enter image description here
stats table:enter image description here
StatsController:
public function index(){
$stats = Stats::all();
return view('stats', ['stats' => $stats]);
}
public function addstats(){
if($this->request->method() == 'POST'){
$alert = request() -> validate([
'points' => 'required|numeric',
'average_points' => 'required|numeric',
'games' => 'required|numeric',
'duration' => 'required|numeric'
]);
$stats = new Stats;
$stats->player_id = $this->request->id;
$stats->points = $this->request->get('points');
$stats->average_points = $this->request->get('average_points');
$stats->games = $this->request->get('games');
$stats->duration = $this->request->get('duration');
if($stats -> save()){
echo 'Success';
}
}
return view('addstats', ['player_id' => $this->request->player_id]);
}
public function editstats(Stats $stats){
if($this->request->method() == 'POST'){
$alert = request() -> validate([
'points' => 'required|numeric',
'average_points' => 'required|numeric',
'games' => 'required|numeric',
'duration' => 'required|numeric'
]);
$stats->player_id = $this->request->id;
$stats->fullname = $this->request->get('points');
$stats->age = $this->request->get('average_points');
$stats->height = $this->request->get('games');
$stats->weight = $this->request->get('duration');
if($stats -> save()){
return redirect('stats/');
}
}
return view('editstats', ['stats' => $stats]);
}
public function destroy(Stats $stats){
$stats->delete();
return redirect('stats/');
}
addstats blade php:
#section('content')
<div class="container">
<form action="{{route('addstats')}}" method="POST">
#csrf
<input type="hidden" name="id" value="{{$player_id}}">
<p>Overall Points:</p>
<input type="number" name="points" class="form-control" value="{{Request::old('points')}}" required>
<p style="color: red">#error('points') {{$message}} #enderror</p>
<p>Average points per game:</p>
<input type="number" name="average_points" class="form-control" value="{{Request::old('average_points')}}" required>
<p style="color: red">#error('average_points') {{$message}} #enderror</p>
<p>Games:</p>
<input type="number" name="games" class="form-control" value="{{Request::old('games')}}" required>
<p style="color: red">#error('games') {{$message}} #enderror</p>
<p>Duration:</p>
<input type="number" name="duration" class="form-control" value="{{Request::old('duration')}}" required>
<p style="color: red">#error('duration') {{$message}} #enderror</p>
<button class="btn btn-primary">Submit</button>
</form>
</div>
#endsection
my Routes:
Route::middleware('auth')->group(function(){
Route::get('/', [PlayersController::class, 'index']);
Route::post('/addplayer', [PlayersController::class, 'addplayer'])->name('addplayer');
Route::get('/addplayer', [PlayersController::class, 'addplayer'])->name('addplayer');
Route::get('/editplayer/{players}', [PlayersController::class, 'editplayer'])->name('editplayer');
Route::post('/editplayer/{players}', [PlayersController::class, 'editplayer'])->name('editplayer');
Route::get('/destroy/{players}', [PlayersController::class, 'destroy'])->name('destroy');
Route::get('/stats/{player_id?}', [StatsController::class, 'index']);
Route::post('/addstats', [StatsController::class, 'addstats'])->name('addstats');
Route::get('/addstats', [StatsController::class, 'addstats'])->name('addstats');
Route::get('/editstats/{stats?}', [StatsController::class, 'editstats'])->name('editstats');
Route::post('/editstats/{stats?}', [StatsController::class, 'editstats'])->name('editstats');
Route::get('/destroy/{stats?}', [StatsController::class, 'destroy'])->name('destroy');
});
class Stats extends Model
{
use HasFactory;
protected $table = 'stats';
protected $fillable = [
'player_id','points','average_points','games','duration'
];
}

My model always give empty even I have data in database Laravel 5

UPDATE
I just found the problem here, it is typo at $instID = $request->insititution;
It should be $instID = $request->institution;
Thanks for all your helps..
UPDATE
I trying to insert to CRConfigDetail Model / table, but first I need to get my CRConfigID from CRConfig Model / Table with specific rules. So I can get the CRConfigID and put it to CRConfigDetail column.
But every time I trying to retrieve, it always give empty data even I already have data at my database. In other Controller I can retrieve data with similar rules.
Am I do something wrong with logic? Because I don't see any errors.
Here is my HTML / form:
<form action="doInsertSCC" method="POST" enctype="multipart/form-data" id="scheduleDetailForm">
{{csrf_field()}}
<div class="form-group">
<label for="institution">Institution</label>
<select name="institution" class="form-control" id="institution">
</select>
</div>
<div class="form-group">
<label for="acadCareer">Academic Career</label>
<select name="acadCareer" class="form-control" id="acadCareer">
</select>
</div>
<div class="form-group">
<label for="period">Period</label>
<select name="period" class="form-control" id="period">
</select>
</div>
<div class="form-group">
<label for="department">Department</label>
<select name="department" class="form-control" id="department">
</select>
</div>
<div class="form-group">
<label for="fos">Field of Study</label>
<select name="fos" class="form-control" id="fos">
</select>
</div>
<div class="form-group">
<label for="scc">Lecturer's ID - Name</label>
<select name="scc" class="form-control" id="scc">
</select>
</div>
<button type="submit" class="btn btn-default">Assign SCC</button>
<div id="search" class="btn btn-default">Search</div>
</form>
Here is my Route to access my Controller
Route::post('/doInsertSCC', "ScheduleController#insertSCC");
And here is my ScheduleController
public function insertSCC(Request $request){
$this->validate($request, [
'scc' => 'required'
]);
$instID = $request->insititution;
$acadID = $request->acadCareer;
$termID = $request->period;
$depID = $request->department;
$rule = ['institutionID' => $instID, 'acadCareerID' => $acadID, 'termID' => $termID, 'departmentID' => $depID];
$crConfig = CRConfig::where($rule)->first();
if( !empty($crConfig) ){
foreach ($crConfig as $cr) {
$crConfigID = $cr->CRConfigID;
}
$schedule = new CRConfigDetail;
$schedule->status = 'Pending';
$schedule->numRevision = 0;
$schedule->FOSID = $request->fos;
$schedule->SCC = $request->scc;
$schedule->CRConfigID = $crConfigID;
$schedule->save();
return redirect("AssignSCC")->with('status', 'Add SCC success!');
}else{
return redirect("AssignSCC")->with('status', 'Add schedule first!');
}
}
I already check my rules data are match with my CRConfig table's data (using console.log()
Everytime I submit this form, I will do the "else" and redirect with "Add schedule first!" message.
Actually, it does accept an array, but the array should be formatted as such..
$rule = [
['institutionID', '=', $instID],
['acadCareerID', '=', $acadID],
['termID', '=', $termID],
['departmentID', '=', $depID]
];
Source: https://laravel.com/docs/5.4/queries#where-clauses
use the below one
$crConfig = CRConfig::where('institutionID' , $instID)
->where('acadCareerID' , $acadID)
->where('termID', $termID)
->where('departmentID', $depID)
->first();
instead of
$rule = ['institutionID' => $instID, 'acadCareerID' => $acadID, 'termID' => $termID, 'departmentID' => $depID];
$crConfig = CRConfig::where($rule)->first();
You can check the query built at the backend by getting the query log, for this you have to enable the query log before the query gets built and get the query log after the query gets built both query log methods belongs to DB facade
\DB::enableQueryLog();
\DB::getQueryLog();

Resources