SQLSTATE[HY000]: General error: 1364 Field 'title' doesn't have a default value - laravel

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

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.

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 Illuminate\Database\Eloquent\Model;
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');
}

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:

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 App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
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();
...
}

Related

updateOrCreate - Laravel 8

I just started learning Laravel. I can't figure out how to update the data in the table. There is a table:
I want to insert the entry: machine_name + number_of_shifts. At the same time, if there is a machine_name record, then the number_of_shifts value must be updated for this record. Or, if there is no record, then create a new machine_name + number_of_shifts.
As a result, the error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: update `machines` set `machine_name` = Станок 456, `machines`.`updated_at` = 2023-01-16 20:52:34 where `id` is null)
What did I prescribe wrong?????? HELP ME FIGURE IT OUT, please.
Controller Code StoreController:
<?php
namespace App\Http\Controllers\Machines;
use App\Http\Controllers\Controller;
use App\Models\Machine;
use Illuminate\Http\Request;
class StoreController extends Controller
{
public function __invoke(Request $request){
$data = request()->validate([
'machine_name' => '',
'number_of_shifts' => '',
]);
Machine::updateOrCreate(['number_of_shifts' => $request->input('number_of_shifts')], $data);
return redirect()->route('machine.index');
}
}
Code create.blade
#extends('layouts.main')
#section('title-block') Добавить станок #endsection
#section('content')
<div class="d-flex p-2">
<form action="{{ route('machine.store') }}" method="post">
#csrf
<div class="mb-3">
<label for="machine_name" class="form-label">Станок</label>
<input type="text" name="machine_name" class="form-control" id="machine_name" placeholder="Станок 1">
</div>
<div class="mb-3">
<label for="number_of_shifts" class="form-label">Количество смен</label>
<input type="text" name="number_of_shifts" class="form-control" id="number_of_shifts" placeholder="1">
</div>
<button type="submit" class="btn btn-dark">Добавить станок</button>
<a class="btn btn-dark" href="{{ route ('machine.index') }}" role="button">Назад</a>
</form>
</div>
#endsection
Migration Code:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('machines', function (Blueprint $table) {
$table->id('machine_id');
$table->string('machine_name', 255);
$table->bigInteger('number_of_shifts')->unsigned()->nullable()->default(0);
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('machines');
}
};
If you have changed the primary key name then you most define in model like this.
protected $primaryKey = 'machine_id';
And this is the bad idea to change its primary key.

How can I save records in attendance table using Laravel?

I am having issue with saving attendance record of student in attendance listings. The frontend part is working well but record saved in backend of attendance table is not shown. How can I save record in backend table of attendance which consists of level_id, teacher_id and student_id
Here is my attendance migrations table
$table->id();
$table->unsignedBigInteger('level_id');
$table->unsignedBigInteger('teacher_id');
$table->unsignedBigInteger('student_id');
$table->foreign('level_id')->references('id')->on('levels');
$table->foreign('teacher_id')->references('id')->on('teachers');
$table->foreign('student_id')->references('id')->on('students');
$table->date('attendance_date');
$table->string('attendance_status');
$table->timestamps();
Here is my students migrations tables
$table->id();
// The Parents table must exist and Must have 'id' as Primary Key
$table->unsignedbiginteger('parent_id');
$table->unsignedbiginteger('level_id');
$table->foreign('parent_id')->references('id')->on('parents')
->onDelete('cascade');
$table->foreign('level_id')->references('id')->on('levels');
$table->string('student_roll_no');
$table->string('student_surname');
$table->string('student_middle_name')->nullable();
$table->string('student_given_name');
$table->string('student_place_of_birth');
$table->date('student_date_of_birth');
$table->string('student_gender');
$table->text('student_home_address');
$table->string('student_suburb')->nullable();
$table->string('student_post_code');
$table->string('student_home_phone')->nullable();
$table->string('student_work_phone')->nullable();
$table->string('student_mobile_phone');
$table->string('student_email')->nullable();
$table->string('student_photo')->nullable();
$table->string('language_spoken_at_home')->nullable();
$table->string('school_name');
$table->string('student_semester')->nullable();
$table->string('school_suburb')->nullable();
$table->text('school_address')->nullable();
$table->string('student_oversea_full_paying')->nullable();
$table->string('emergency_person_one_name')->nullable();
$table->string('emergency_person_one_mobile_number');
$table->string('emergency_person_one_house_number')->nullable();
$table->string('emergency_person_two_name')->nullable();
$table->string('emergency_person_two_mobile_number')->nullable();
$table->string('emergency_person_two_house_number')->nullable();
$table->string('medical_condition')->nullable();
$table->boolean('medical_health_support')->nullable();
$table->boolean('family_court_orders');
$table->string('family_court_file')->nullable();
$table->boolean('authority_to_school_staff');
$table->boolean('authorize_school_staff_to_arrange_medical_treatment');
$table->boolean('authorize_school_staff_administering_medication');
$table->boolean('notify_the_school_absent');
$table->boolean('withdraw_child_from_school');
$table->boolean('authorize_photograph_to_school');
$table->boolean('authorize_child_name_school_newsletter_website');
$table->boolean('authorize_short_local_walks');
$table->boolean('authorize_participate_in_any_incursions');
$table->boolean('information_contained_in_this_form_correct');
$table->boolean('status')->default(1);
$table->timestamps();
Here is my levels tables
$table->bigIncrements('id');
$table->string('level_name');
$table->timestamps();
Here is my Teachers migrations tables
$table->id();
// The Parents table must exist and Must have 'id' as Primary Key
$table->unsignedbiginteger('user_id')->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->string('teacher_name');
$table->string('teacher_email')->unique();
$table->string('teacher_home_phone')->nullable();
$table->string('teacher_mobile_phone');
$table->string('teacher_work_phone')->nullable();
$table->string('teacher_home_address');
$table->string('teacher_suburb')->nullable();
$table->string('teacher_postcode');
$table->timestamps();
Here is my Attendance Controller
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Levels;
use App\Models\Teacher;
use App\Models\Student;
use App\Models\Attendance;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class AttendanceController extends Controller
{
/**
* Create a new controller instance
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index($level_id = NULL)
{
$levels = Levels::all();
$students = Student::all();
return view('admin.attendance.list', compact( 'levels', 'students','level_id'));
}
/**
* Perform Actions in attendance.add
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function add()
{
$levels = array();
$students = array();
return view('admin.attendance.add', compact('levels', 'teachers'));
}
/**
* Store values in application dashboard
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function store(Request $request, $level_id)
{
//get form data
$data = $request->all();
//Creeate Student record
$students = Student::all();
$levels = Levels::all();
if($level_id){
$levels = Levels::find($level_id);
if($levels){
$attendance = Attendance::with(['student', 'levels'])->first();
return view('admin.attendance.add', compact('students','level_id', 'levels', 'attendance'));
}
}
}
}
Here is my Attendance model
public function student()
{
return $this->belongsTo(Student::class,'student_id');
}
public function teacher()
{
return $this->belongsTo(Teacher::class, 'teacher_id');
}
public function levels()
{
return $this->belongsTo(Levels::class, 'level_id');
}
Here is my list.blade.php file of containing attendance
#section('content')
#if(session()->has('message'))
<div class="row">
<div class="col-md-12">
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
</div>
</div>
#endif
#if(isset($levels) || $levels == '')
<div class="form-row justify-content-center">
<div class="form-group col-xs-6">
<label for="Date"> Please Select Date</label>
<input type="date" name="attendance_date" value="{{ date('Y-m-d') }}" class="form-control" required>
</div>
<div class="form-group col-xs-6">
<label for="Attendance">Please Select Level to see registered students</label>
<select class="form-control" id="level_id" name="student_id">
<option value="" disabled selected>Select Level</option>
#foreach($levels as $level)
<option value="{{#$level->id}}">{{#$level->level_name}}</option>
#endforeach
</select>
</div>
</div>
#endif
#stop
#section('js')
<script>
jQuery(document).ready(function($) {
// get your select element and listen for a change event on it
$('#level_id').change(function() {
// set the window's location property to the value of the option the user has selected
window.location = '/attendance/add/'+$(this).val();
});
});
</script>
#endsection
Here is my add.blade.php file containing attendance
<form action="{{ route('attendance.index') }}" method="GET" class="w-full max-w-xl px-6 py-12" enctype="multipart/form-data">
#csrf
#php
$heads = [
'Name',
'Roll Number',
'Semester',
['label' => 'Attendance', 'no-export' => true, 'width' => 5],
];
/*$btnDetails = '<button class="btn btn-xs btn-default text-teal mx-1 shadow" title="Details">
<i class="fa fa-lg fa-fw fa-eye"></i>
</button>';*/
$config = [
'data' => $students,
'order' => [[1, 'asc']],
'columns' => [null, null, null, null, ['orderable' => true]],
];
#endphp
{{-- Minimal example / fill data using the component slot --}}
<x-adminlte-datatable id="table6" :heads="$heads" head-theme="light" theme="light custom-head-theme dt-responsive"
striped>
#if($config['data'])
#foreach($config['data'] as $row)
<tr class="{{ (isset($row['status']) && $row['status']==0) ? 'table-danger' : ''}}">
<td>{!! $row['student_given_name'] !!}</td>
<td>{!! $row['student_roll_no']!!}</td>
<td>{!! $row['student_semester']!!}</td>
<td>
<nobr>
<select class="form-control" name="attendance_status" value="{{old('attendance_status'), #$attendance->attendance_status}}" id="attendance_status" required>
<option value="" {{#$attendance->attendance_status == '' ? 'selected' : ''}} disabled selected>Select Option</option>
<option value="Present" {{#$attendance->attendance_status == 'present' ? 'selected' : ''}} selected>Present</option>
<option value="Absent" {{#$attendance->attendance_status == 'absent' ? 'selected' : ''}}>Absent</option>
</select>
<input type="text" name="textinput" id="level_id" placeholder="Reason">
</nobr>
</td>
</tr>
#endforeach
#endif
</x-adminlte-datatable>
<div class="row mt-3">
<div class="col-md-12">
<div class="card-footer">
<div class="float-left col-md-4 mb-2">
<button type="submit" name="save_close" value="true" class="btn btn-primary btn-lg btn-block">Save & Close</button>
</div>
<div class="float-right col-md-4 mb-2">
<button type="button" class="btn btn-secondary btn-lg btn-block">Cancel</button>
</div>
</div>
</div>
</div>
</form>
#stop
What modifications are required in attendance controller in order to save record in table and I can view it on frontend side as well
On your AttendanceController you just show data, not insert data to database, you should get the request data and insert data to database, but first check your blade file, you must make an input for level_id, teacher_id, and student_id
to check your attachment you can use
dd($request);
die();
on your first line AttendanceController function store
public function store(Request $request, $level_id)
{
dd($request);
die();
//get form data
$data = $request->all();
//Create Student record
$students = Student::all();
$levels = Levels::all();
if($level_id){
$levels = Levels::find($level_id);
if($levels){
$attendance = Attendance::with(['student', 'levels'])->first();
return view('admin.attendance.add', compact('students','level_id', 'levels', 'attendance'));
}
}
}
if your system catch the good request
you should try this
public function store(Request $request, $level_id)
{
$levels_id = $request->level_id;
$teachers_id = $request->teacher_id;
$students_id = $request->student_id;
$data = [$levels_id,teachers_id,students_id];
attendance::create($data);
}
there's the code to save data into your laravel project, you should approve my solution

Laravel 8 form select option dropdown problem

Am having problem here
I have two tables
Department table
with fields
id dept_code dept_name
I also have Persons table
with fields
id Persons_names Dept_name Position_held
I have a data entry form to enter data to the Persons_table
the problem am having is I want to create select option to get Dept_name From Department_table but am always getting undefined value error.
this is my form
{!! Form::open(['url' => 'persons_form/store']) !!}
{{ csrf_field() }}
<div class="form-row">
<div class="form-group col-md-6">
{{Form::label('FullNames', 'Fullnames')}}
{{Form::text('names', '',['class'=>'form-control','placeholder'=>'Persons Fullnames'])}}
</div>
<div class="form-group col-md-6">
{{Form::label('Department', 'Department')}}
#foreach ($depts as $dept)
{{
Form::select('department', $dept->department_name, null, ['class'=>'form-control','placeholder' => 'Select Department'])
}}
#endforeach
</div>
<div class="form-group col-md-12">
{{Form::label('Position', 'Position')}}
{{Form::text('level', '',['class'=>'form-control','placeholder'=>'Departmental Position'])}}
</div>
</div>
<div>
{{Form::submit('Save Data',['class'=>'btn btn-outline-primary text-center',])}}
</div>
{!! Form::close() !!}
this is my personsController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\People;
class PeopleController extends Controller
{
public function index()
{
$depts = DB::table('departments')->select('department_name')->get();
return view('strategic_plan.people_form', ['depts' => $depts]);
}
public function create()
{
$depts = DB::table('departments')->pluck('department_name');
}
public function store(Request $request)
{
$this->validate($request,[
'names'=>'required',
'department'=>'required',
'level' =>'required'
]);
$persons =new People;
$persons->names=$request->input('names');
$persons->department=$request->input('persons');
$persons->level=$request->input('level');
$dept->save();
return redirect('/people')->with('message','Person Added Succesifully');
}
public function show()
{
$persons = People::all()->sortByDesc("id");
return view('strategic_plan.people',compact('persons'));
}
public function edit($id)
{
}
public function update(Request $request, $id)
{
//
}
public function destroy($id)
{
//
}
}
When I try to open the Form am getting
$depts is undefined
Try using compact, And get #dd in your blade of $depts and share the code.
Use
return view('strategic_plan.people_form', ['depts' => $depts]);
instead of
return view('strategic_plan.people_form', compact('depts');
write it down

Property [costo] does not exist on this collection instance

i need to print the price of a service, but can't find the column with the price.
maybe I'm doing something wrong with relationships, but I can't figure it out on my own
database:
Controller:
public function details(Request $request,$id){
$datax = [
'category_name' => 'apps',
'page_name' => 'calendar',
'has_scrollspy' => 0,
'scrollspy_offset' => '',
];
$evento = Eventos::find($id);
$servicio = \App\Models\Eventos::select("servicio_id")->where('servicio_id', $evento->id)->get('servicio_id');
$event = Eventos::find($id);
$event->asistencia = $request->asistencia;
$event->cancelado = $request->cancelado;
$event->save();
return view("evento",[
"event" => $event,
"servicio" => $servicio
])->with($datax);
}
blade.php
<div class="input-group mb-4">
<div class="input-group-prepend">
<span class="input-group-text">$</span>
</div>
<input type="text" value="{{$servicio->costo}}" class="form-control col-md-3" aria-label="Amount (to the nearest dollar)">
<div class="input-group-append">
<span class="input-group-text"></span>
</div>
</div>
I need to print the "costo" column in relation to service_id
help please
you can use laravel elequent relationship one to one.
if you have this two Servicio.php & Evento.php in App/Models or whatever your models name is, only replace your models in below code do this:
1-
in App/Models/Servicio.php define this relationship:
public function evento()
{
return $this->hasOne(Evento::class);
}
in App/Models/Evento.php define this relationship:
public function servicio()
{
return $this->belongsTo(Servicio::class);
}
now in controller add this:
$evento = Eventos::where('id' , $id)->with('servicio')->first();
in blade use this:
<input type="text" value="{{$evento->servicio->costo}}" >
2- also you can do this but i suggest you the first one:
only in your Codes change this:
$servicio = \App\Models\Servicio::where('id', $evento->servicio_id)->first();

Update Comment in Laravel

I am new at Laravel and I want to use if statement inside Laravel Controller.
So I have a form tag where I can add comments. I want to edit comments in the same form.
Here is my form tag:
<form method="post" action="/hotels/{{$id}}" name="review_hotel">
#csrf
<div class="form-group">
<textarea name="comment" id="comment" class="form-control" style="height:100px"
placeholder="Write your review"></textarea>
#error('comment')
<p class="text-danger">{{$message}}</p>
#enderror
</div>
<input type="submit" value="Submit" class="btn_1" id="submit-review">
</form>
I have a script, with the help of this script I can add a comment that I want to change to the textarea.
After this I have no idea how to update it in my controller.
This is CommentController:
public function comment(CommentRequest $request, $id)
{
$comment = new Comment();
$comment->object_id = $id;
$comment->user_id = Auth::id();
$comment->comment = $request['comment'];
$comment->save();
return redirect('/hotels/'.$id);
}
I think I need to write "if" statement in my controller, but I don't know how.
maybe there is a simpler way to update comment?
On your model Comment.php mark form variables as fillable
public $fillable = ['object_id', 'user_id', 'comment'];
then use this Model function (Eloquent)
Comment::updateOrCreate(
[
'object_id' => ...,
'user_id' => ...,
],
[
'object_id' => ...,
'user_id' => ...,
'comment' => ...,
]
);
https://laravel.com/docs/5.8/eloquent#other-creation-methods

Resources