Failed to save value select option - laravel

what's wrong in my project.
I want to save with select option, but the filed doesn't save data select option. it just save input text.
the project is taken different table, and the form just get the project_name and project_id. project_id will save in in table spent_times.
and the select option will save task_category in table spent_times
this my model
protected $table = 'spent_times';
protected $fillable = [
'task_category',
'story/meeting_name',
'assign',
'estimated_time',
'user_story',
'spent_time',
'percentage',
'lateness',
'index',
'project_id'
];
public function users() {
return $this->hasMany(User::class);
}
public function project() {
return $this->belongsTo(Project::class);
}
my create.blade.php
<form action="{{route('store')}}" method="POST">
#csrf
<div class="box-body">
<div class="form-group">
<label for="">Project *</label>
<select class="form-control select2" style="width: 100%;">
<option>Select One</option>
#foreach($projects as $id => $project)
<option value="{{$id}}">{{$project}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="">Story # Meeting Name *</label>
<input type="text" class="form-control" name="user_story">
</div>
<div class="form-group">
<label for="">Category *</label>
<select class="form-control select2" style="width: 100%;">
<option>Select One</option>
#foreach($task_categories as $category)
<option value="{{$category}}">{{$category}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="">Estimated *</label>
<input type="text" class="form-control" name="estimated_time">
</div>
</div>
<div class="box-footer">
<a href="{{route('index')}}">
<button type="submit" class="btn btn-primary col-md-12" style="border-radius : 0px;">SAVE</button>
</a>
</div>
</form>
my controller
public function create()
{
$spentimes = new SpentTime;
$project = new Project;
$projects = Project::select('project_name', 'id')->get();
return view('Ongoings.index', compact ('projects', 'task_categories', 'spentimes', 'project'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
dd($request->all());
$spentime = SpentTime::create([
'project_name' => request('project_name'),
'user_stroy' => request ('user_story'),
'task_category' => request('task_category'),
'estimated_time' => request('estimated_time')
]);
$spentime->save();
return redirect()->route('index');
}
error like this
error in web browser
please help me

You are expecting those fields from request in controller.
project_id
meeting_name
task_category
estimated_time
But You are just sending estimated_time,
other 3 fields are not present in you create.blade.php
In create.blade.php, category select input don't have any name.
that's why task_category is getting null from request('task_category'). But task_category field is not nullable in your database table.
Send form input properly as you are expecting in your controller. You can use dd($request->all()) to check.

I believe this is your task_category select box.
so this select box doesn't have a name attribute. that's the error.
Possible solution.
<div class="form-group">
<label for="">Category *</label>
<select name="task_category" class="form-control select2" style="width: 100%;">
<option>Select One</option>
#foreach($task_categories as $category)
<option value="{{$category}}">{{$category}}</option>
#endforeach
</select>
</div>

Related

Using Select in an Edit Form Laravel

Im trying to implement a Edit function to update permissions from an Laravel User, (I already installed Spatie), it parcially works, it save the changes but I cant see the permissions of the role on the Select Form. Any help please
<--CONTROLLER-->
public function edit($id)
{
$role = Role::findById($id);
$permissions = Permission::all();
return view('admin_roles_edit', compact('role','permissions', 'permissions1'));
}
public function update(Request $request, $id)
{
$request->validate([
'name'=>'required|max:30',
]);
$role = Role::findById($id);
$role->update($request->all());
$role->permissions()->sync($request->permissions);
return redirect()->route('admin.roles.index')->with('message', 'El rol se ha actualizado correctamente');
}
<--HTML-->
<form action="{{route('admin.roles.update', $role->id)}}" method="post"
class="form">
#csrf
<div class="form-group has-feedback">
<label class="control-label col-lg-3">Nombre<span
class="text-danger">*</span></label>
<input type="text" class="form-control" name="name"
value="{{$role->name}}" required="required">
#error('name')
<label class="validation-error-label" for="basic">{{$message}}</label>
#enderror
</div>
<div class="form-group has-feedback">
<label class="control-label col-lg-3">Permisos<span
class="text-danger">*</span></label>
<div class="multi-select-full">
<select class="multiselect" multiple="multiple" name="roles">
#foreach($permissions as $permission)
<option value="{{$permission->id}} #if($permission->id == $role->permission) selected #endif">{{$permission->name}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group pull-right">
<a href="{{route('admin.roles.index')}}" type="button" class="btn btn-default"><i
class="icon-cross2 position-left"></i>Cancelar
</a>
<button type="submit" class="submit-btn btn btn-success"><i
class="icon-add position-left"></i>Editar
</button>
</div>
</form>
<--RESULT-->
in your controller add this line:
public function edit($id)
{
$role = Role::findById($id);
$permissions = Permission::all();
$rolePermissions = $role->permissions()->pluck('name','id')->toArray();
return view('admin_roles_edit', compact('role','permissions', 'rolePermissions'));
}
update your blade:
<option value="{{$permission->id}}" {{in_array($permission->id, array_keys($rolePermissions)) ? 'selected' : '')}}>{{$permission->name}}</option>
Fixed finally
RoleController.php
public function edit($id)
{
$role = Role::findById($id);
$permissions = Permission::all();
return view('admin_roles_edit', compact('role','permissions'));
}
RoleView.blade.php
<select class="multiselect" multiple="multiple" name="roles">
#foreach($permissions as $permission)
<option value="{{$permission->id}}"
#if($role->hasPermissionTo($permission->id))
selected="selected"
#endif/>{{$permission->name}}</option>
#endforeach
</select>
Fixed Result

Laravel - Validate textinput value with database value

I am using Laravel-5.8 for a web application. In the project I want the users to set goals using these two tables:
class GoalType extends Model
{
protected $table = 'goal_types';
protected $fillable = [
'name',
'parent_id',
'is_current',
'max_score',
];
public function children()
{
return $this->hasMany('App\Models\GoalType', 'parent_id');
}
public function goals()
{
return $this->hasMany('App\Models\Goal');
}
}
class Goal extends Model
{
protected $table = 'appraisal_goals';
protected $fillable = [
'goal_type_id',
'employee_id',
'weighted_score',
'goal_description',
'goal_title',
];
public function goaltype()
{
return $this->belongsTo('App\Models\GoalType','goal_type_id');
}
}
As shown in the diagram below, GoalType is an hierarchical table. Only the parent have the max_score:
Controller
public function create()
{
$userCompany = Auth::user()->company_id;
$categories = GoalType::with('children')->where('company_id', $userCompany)->whereNull('parent_id')->get();
return view('goals.create')
->with('categories', $categories);
}
public function store(StoreGoalRequest $request)
{
$employeeId = Auth::user()->employee_id;
$goal = new Goal();
$goal->goal_type_id = $request->goal_type_id;
$goal->employee_id = $employeeId;
$goal->weighted_score = $request->weighted_score;
$goal->save();
Session::flash('success', 'Goal is created successfully');
return redirect()->route('goals.index');
}
create.blade
<div class="row">
<div class="col-md-12">
<!-- general form elements -->
<div class="card card-secondary">
<!-- /.card-header -->
<!-- form start -->
<form method="POST" action="{{route('goals.store')}}">
#csrf
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Goal Type:<span style="color:red;">*</span></label>
<select id="goal_type" class="form-control" name="goal_type_id">
<option value="">Select Goal Type</option>
#foreach ($categories as $category)
#unless($category->name === 'Job Fundamentals')
<option disabled="disabled" value="{{ $category->id }}" {{ $category->id == old('category_id') ? 'selected' : '' }}>{{ $category->name }}</option>
#if ($category->children)
#foreach ($category->children as $child)
#unless($child->name === 'Job Fundamentals')
<option value="{{ $child->id }}" {{ $child->id == old('category_id') ? 'selected' : '' }}> {{ $child->name }}</option>
#endunless
#endforeach
#endif
#endunless
#endforeach
</select>
</div>
</div>
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Goal Title:<span style="color:red;">*</span></label>
<input type="text" name="goal_title" placeholder="Enter goal title here" class="form-control">
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label>Goal Description</label>
<textarea rows="2" name="goal_description" class="form-control" placeholder="Enter Goal Description here ..."></textarea>
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Weight:</label>
<input type="number" name="weighted_score" placeholder="Enter weighted score here" class="form-control">
</div>
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
<button type="button" onclick="window.location.href='{{route('goals.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
</div>
<!-- /.card -->
</div>
<!--/.col (left) -->
</div>
From the diagram above, GoalType (goal_type_id) dropdown contains all the children fields from goal_types. What I want to achieve is this:
When Goal Type is selected from the dropdown, the system goes to the goals table (Goal). It displays total weighted_score based on employee_id and goal_type_id.
When the user tries to enter data into weight text field (weighted_score), the application adds the value in the text field to the result in number one (1) above. If the result is more than the max_score in goal_types (GoalType) based on the parent max_score, then an error message is displayed.
How do I achieve this?
Thank you.
You have to use AJAX for this, if you're unfamiliar with it, you can read about it here: https://www.w3schools.com/xml/ajax_intro.asp
I would also use JQuery to make things simpler. This way, you can do like this:
When Goal Type is selected from the dropdown, the system goes to the goals table (Goal). It displays total weighted_score based on employee_id and goal_type_id.
here you have to send to backend the goal type the user selected, for that, set an on change event in the combobox that triggers the AJAX request:
$('#goal_type').change(request_goals($('#goal_type').val()))
And the request_goals function should be like this:
function request_goals(){
$.ajax({
method: "GET",
dataType: 'json',
url: /*YOUR CONTROLLER URL*/,
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
console.log("error");
},
success: function (response) {
/* HERE DO WHAT YOU NEED */
}
}
You will have to create a route and a controller function that returns the data you need.
When the user tries to enter data into weight text field (weighted_score), the application adds the value in the text field to the result in number one (1) above. If the result is more than the max_score in goal_types (GoalType) based on the parent max_score, then an error message is displayed.
Here you should do the same trick, set an event handler in the weighted_score field that sends an ajax request.
I hope it can help you.
If you want to archive it without AJAX calls, you can submit the form on select box change: <select name="goal_type_id" onchange="this.form.submit()">
In the controller you can catch the old input with old("goal_type_id"). You can query/calculate now the total weighted_score.

Laravel - How to Make Lesson aggregate score not more than course max score

I am developing a web application on Student Course Management using Laravel-5.8
Models
class Lesson extends Model
{
protected $table = 'Lessons';
protected $fillable = [
'lesson_name',
'course_id',
'student_id',
'score_obtained',
];
public function gradelevel()
{
return $this->belongsTo('App\Models\Course','course_id');
}
public function student()
{
return $this->belongsTo('App\Models\Student','student_id');
}
}
class Course extends Model
{
protected $table = 'courses';
protected $fillable = [
'course_code',
'course_name',
'max_score',
];
}
Controller
class LessonController extends Controller
{
public function create()
{
$courses = Course::all();
$students = Student::all();
return view('lessons.create')->with('courses', $courses)->with('students', $students);
}
public function store(StoreLessonRequest $request)
{
try {
$lesson = Lesson::create([
'lesson_name' => $request->lesson_name,
'course_id' => $request->course_id,
'lesson_id' => $request->lesson_id,
'score_obtained' => $request->score_obtained,
]);
Session::flash('success', 'Lesson is created successfully');
return redirect()->route('lessons.index');
} catch (Exception $exception) {
Session::flash('danger', 'Lesson creation failed!');
return redirect()->route('lessons.index');
}
}
}
create.blade
<form action="{{route('lessons.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label>Course</label>
<select class="form-control select2bs4" data-placeholder="Choose Course" tabindex="1" name="course_id" style="width: 100%;">>
<option value="">Select Course</option>
#if($courses->count() > 0)
#foreach($courses as $course)
<option value="{{$course->id}}">{{$course->course_name}}</option>
#endforeach
#endif
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Student</label>
<select class="form-control select2bs4" data-placeholder="Choose Course" tabindex="1" name="student_id" style="width: 100%;">>
<option value="">Select Student</option>
#if($students->count() > 0)
#foreach($students as $student)
<option value="{{$student->id}}">{{$student->student_name}}</option>
#endforeach
#endif
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Lesson<span style="color:red;">*</span></label>
<input type="text" name="lesson_name" placeholder="Enter lesson here" class="form-control" value="{{old('lesson_name')}}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Obtained Score<span style="color:red;">*</span></label>
<input type="text" name="score_obtained" placeholder="Enter score obtained here" class="form-control" value="{{old('score_obtained')}}">
</div>
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" id="submit_create" class="btn btn-primary">Score</button>
</div>
</form>
Each core have maximum score allocated and this is done at the setting. For each course, students have lesson and scores are obtained for each lesson.
What I want to achieve is that on the lesson create form, what student score_obtained are being entered the application should sum up all the scores (from the lesson table and the just entered one) the student obtained for that particular course including the one in the textbox, if its more that what is in the max_score in the courses table for that particular course the application should display a message and shouldn't allow the user to submit.
How do I achieve this?
Thank you.
In store method, you can write below code:
$maxScore = Course::find($request->course_id)->max_score;
$scoresObtained = Lession::where('course_id' , $request->course_id)->sum('score_obtained');
$totalScore = intval($scoresObtained) + intval($request->score_obtained);
if($totalScore > $maxScore)
{
return redirect()->back()->withErrors([__('Total score exceeds max score for selected course')]);
}
You can use floatval() in place of intval() in case your scores are in decimals

data isn't saving into db using eloquent relation

hi m trying to save data into db using Eloquent ORM one-to-one but it is not saving and not showing any error to fix it (m unable to find any solution about it because it is not showing any error),
public function store(Request $request)
{
$request->validate([
'owner_id' => 'required',
'phone_name' => 'required|unique:phones'
]);
$phone = new Phone;
$phone->owner_id = $request->owner_id;
$phone->phone_name = $request->phone_name;
$phone->save();
return redirect()->route('phone.index')->with('flash_messages_success', 'Phone has been added successfully');
}
protected $fillable = [
'pphone_name', 'owner_id'
];
public function owner()
{
return $this->belongsTo('App\Owner');
}
<form method="POST" action="{{ route('phone.store') }}">
#csrf
<div class="form-group">
<label for="">Phone Title</label>
<input type="text" name="phone_name" class="form-control" id="" placeholder="Phone Name">
</div>
<div class="form-group">
<label>Select Owner</label>
<select class="form-control" name="category_id">
<option selected="">Under Owner</option>
#foreach($owners as $owner)
<option value="{{ $owner->id }}">{{ $owner->owner_name }}</option>
#endforeach
</select>
</div>
<input type="submit" name="submit" class="btn btn-primary" value="submit">
</form>
The issue in select name you named category_id so the view should be:
<select class="form-control" name="owner_id">

How to insert into pivot table after form submission using attach?

I'm using Laravel eloquent and I'm trying to insert the selected user id from my form and the generated ticket id into my pivot table using attach but I don't know how to do this.
store function
public function store(Request $request
{
$ticket = new Ticket;
$ticket->organisation_name = $request['organisation_name'];
$ticket->postal_address = $request['postal_address'];
$ticket->physical_address = $request['physical_address'];
$ticket->description_brief = $request['description'];
$ticket->hours_dedicated = $request['hours'];
$ticket->commencement_date = $request['start_date'];
$ticket->due_date = $request['due_date'];
$ticket->client_id = $request['client_id'];
$ticket->save();
//trying to use attach here
return redirect('/home');
}
form
<form action="TicketsController#store" method="POST">
{{csrf_field() }}
<div class="form-group">
<label>Organisation Name:</label>
<input type="text" class="form-control" name="organisation_name" placeholder="Enter Organisation Name">
</div>
<div class="form-group">
<label>Postal address:</label>
<input type="text" class="form-control" name="postal_address" placeholder="">
</div>
<div class="form-group">
<label>Physical address:</label>
<input type="text" class="form-control" name="physical_address" placeholder="">
</div>
<div class="form-group">
<label>Client:</label>
<select class="form-control" name="client_id">
#foreach ($forms as $form)
<option>{{$form->client->client_id}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Description:</label>
<input type="text" class="form-control" name="description" placeholder="">
</div>
<div class="form-group">
<label>Hours:</label>
<input type="text" class="form-control" name="hours" placeholder="">
</div>
<div class="form-group">
<label>Start date:</label>
<input type="text" class="form-control" name="start_date" type="date" placeholder="">
</div>
<div class="form-group">
<label>Due date:</label>
<input type="text" class="form-control" name="due_date" type="date" placeholder="">
</div>
<div class="form-group">
<label>User:</label>
<select class="form-control" name="id">
#foreach ($users as $user)
<option>{{$user->id}}</option>
#endforeach
</select>
</div>
<input type="submit" name="submit" class="btn btn-primary">
</form>
User.php
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function tickets(){
return$this->belongsToMany(Ticket::class,'ticket_user','ticket_id','id');
}
Ticket.php
class Ticket extends Model
{
public function client(){
return $this->belongsTo(Client::class,'client_id');
}
public function users(){
return $this->belongsToMany(User::class,'ticket_user','id','ticket_id');
}
protected $primaryKey = 'ticket_id';
public $timestamps = false;
}
As per the documentation you can simply pass the id you want to attach. After $ticket->save(); you can add the following:
$ticket->users()->attach($request->input('id'));
attach() will also work if you pass an array of ids, a model, a collection of ids or a collection of models.

Resources