Search function, only shows two specific people and not others in database - laravel

Using Laravel 5.8 for an assignment on CRUD cricket players and searching them.
My search function only works with one or two specific entries, the first person in my database and one I have created when I add a player.
When I search any other player by first name in the database my results page returns blank.
I have tried different conditional statements and eloquent queries.
Search form
#extends('layout')
#section('content')
<div class="container-fluid">
<div class="row">
<div class="col-md-6">
Search
<form action="/searchresults" method="POST" role="search">
{{ csrf_field() }}
<div class="form-group">
<label for="name">First Name </label>
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First name">
</div>
<div class="form-group">
<label for="name">Last Name </label>
<input type="text" class="form-control" name="lastName" id="lastname" placeholder="Last name">
</div>
<div class="form-group">
<label for="age">Age </label>
<input type="number" class="form-control" name="age" id="age" placeholder="Age" value="age">
</div>
<div class="form-group">
<label for="role">Role </label>
<select class="form-control" name="role" id="role" value="role">
<option> Top-order Batsman </option>
<option> Bowler</option>
<option>Wicketkeeper batsman </option>
<option> Allrounder</option>
<option> Opening Batsman</option>
<option>Wicket Keeper Batsman</option>
<option>Middle-order Batsman</option>
<option>Batting Allrounder</option>
<option>Bowling Allrounder</option>
</select>
</div>
<div class="form-group">
<label for="batting">Batting </label>
<select class="form-control" name="batting" id="batting" value="batting">
<option>Right-hand Bat</option>
<option>Left-hand Bat</option>
</select>
</div>
<div class="form-group">
<label for="Bowling">Bowling</label>
<select class="form-control" name="bowling" id="bowling" value="bowling">
<option> Right-arm offbreak</option>
<option> left-arm fast-medium</option>
<option>Right-arm fast-medium</option>
<option> Right-arm fast</option>
<option>Right-arm medium</option>
<option> legbreak</option>
</option>Left-arm Orthodox</option>
<option>Right-arm spinoff</option>
<option> Slow left-arm Orthodox</option>
</select>
</div>
<div class="form-group">
<label for="odiRuns"> OdiRuns </label>
<input type="number" class="form-control" name="odiRuns" id="odiRuns" value="odiRuns"
placeholder="OdiRuns">
</div>
<div class="form-group">
<label for="Country">Country</label>
<select class="form-control" name="country" id="country" value="country">
<option selected valued=""> Choose...</option>
<option value="All" required>All</option>
#foreach($allcountries as $country)
<option>{{$country->name}}</option>
#endforeach
</select>
<p>(if you dont know the country please select all)</p>
</div>
<button type="submit" class="btn btn-default">Search
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</form>
</div>
</div>
</div>
#endsection
Controller
public function search()
{
$search = request()->all();
$firstName = $search['firstName'];
$lastName = $search['lastName'];
$age = $search['age'];
$role = $search['role'];
$batting = $search['batting'];
$bowling = $search['bowling'];
$odiRuns = $search['odiRuns'];
$country = $search['country'];
$countries = Country::all();
$players = Player::query();
if (!empty($firstName)) {
$players->Where('firstName', 'like', '%' . $firstName . '%');
} elseif (empty($firstName)) {
$players->get();
}
if (!empty($lastName)) {
$players->Where('lastName', 'like', '%' . $lastName . '%');
} elseif (empty($lastName)) {
$players->get();
}
if (empty($age) || $age == 'All') {
$players->get();
} else {
$players->Where('age', $age);
}
if (empty($role) || $role == 'All') {
$players->get();
} else {
$players->Where('role', $role);
}
if (empty($batting) || $batting == 'All') {
$players->get();
} else {
$players->Where('batting', $batting);
}
if (empty($bowling) || $bowling == 'All') {
$players->get();
} else {
$players->Where('bowling', $bowling);
}
if (empty($odiRuns) || $odiRuns == 'All') {
$players->get();
} else {
$players->Where('odiRuns', $odiRuns);
}
if (empty($country) || $country == 'All') {
$players->get();
} else {
$selected = Country::where('name', $country)->get();
$players->where('country', $selected[0]->id);
}
$results = $players->get();
return view('searchresults', compact('results', 'countries'));
}
Results page
#extends('layout')
#section('content')
<table class="table">
<tr scope="row">
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>Role</th>
<th>Batting</th>
<th>Bowling</th>
<th>odiRuns</th>
<th>Country</th>
<th>Player Image</th>
<th>Flag</th>
</tr>
#foreach ($results as $player )
<tr scope="row">
<td>{{$player->firstName}}</td>
<td>{{$player->lastName}}</td>
<td>{{$player->age}}</td>
<td>{{$player->role}}</td>
<td>{{$player->batting}}</td>
<td>{{$player->bowling}}</td>
<td>{{$player->odiRuns}}</td>
<td>{{$player->country->name}}</td>
<td><img src="{{ asset('images/'.$player->image) }}" class="playerimg" /></td>
<td><img src="{{asset('images/'.$player->country->flag)}}" class="flagimg" /></td>
<td>
<form method="POST" action="{{route('player.destroy',$player->id)}}">
{{csrf_field()}}
{{method_field('DELETE')}}
<button type="submit" name="deletePlayer" class="btn btn-secondary btn-md">Del</button>
</form>
</td>
<td><a class="btn btn-primary btn-md" href="{{route('player.edit',$player->id)}}" name="editPlayer"
role="button">Edit</button></td>
</tr>
#endforeach
</table>
#endsection
I would like to view certain players when searched on different aspects, like first name or last name or age, instead, I get the same two results printed the first in my database and one player I have created

Related

Change return View to return Route on laravel search function

I am trying to correct my code of the searchresult function of my controller so my concern is that when I paginate the search result or make form validation, I get the following error message : The GET method is not supported for this route. Supported methods: POST.
so if you can help me, I want to change my code from returning the view to returning the route.
here is my code
Route:
Route::get('/post/searchpost', 'PostsController#index')->name('index');
Route::post('/post/search_result', 'PostsController#searchresult')->name('searchresult');
Blades
//index
<div class="posts">
<h1>Posts</h1>
<div class="sreach">
<form action="{{route('searchresult', app()->getLocale())}}" method="POST">
{{ csrf_field()}}
<div class="form-row">
<div class="form-group col-md-2">
<label class="lbl" for="cat_id">title</label>
<select class="form-control" id="cat_id" name="cat_id">
<option value="" selected></option>
#foreach ($categoriesas $cat)
<option value="{{$cat->id}}">{{$cat->cat_mame}}</option>
#endforeach
</select>
</div>
<div class="form-group col-md-2">
<label class="lbl" for="title">Post title</label>
<input type="text" class="form-control" id="title" name="title">
</div>
<div class="form-group col-md-2">
<label class="lbl" for="content">Post content</label>
<textarea class="form-control" id="content" name="content">
</textarea >
</div>
</div>
<center>
<button type="submit">search</button>
</center>
</form>
</div>
<table id="posts">
<thead>
<tr>
<th>{{__('main.title')}}</th>
<th>{{__('main.post_category')}}</th>
<th>{{__('main.content')}}</th>
</tr>
</thead>
<tbody>
#foreach($posts as $postkey => $post)
<tr>
<td>{{$post->title}}</td>
<td>{{$post->category->cat_name}}</td>
<td>{{$post->content}}</td>
</tr>
#endforeach
</tbody>
</table>
Blades
//searchresult
<div class="posts">
<h1>Posts</h1>
<div class="sreach">
//that make me search again in result page using the same form
<form action="{{route('searchresult', app()->getLocale())}}" method="POST">
{{ csrf_field()}}
<div class="form-row">
<div class="form-group col-md-2">
<label class="lbl" for="cat_id">title</label>
<select class="form-control" id="cat_id" name="cat_id">
<option value="" selected></option>
#foreach ($categoriesas $cat)
<option value="{{$cat->id}}">{{$cat->cat_mame}}</option>
#endforeach
</select>
</div>
<div class="form-group col-md-2">
<label class="lbl" for="title">Post title</label>
<input type="text" class="form-control" id="title" name="title">
</div>
<div class="form-group col-md-2">
<label class="lbl" for="content">Post content</label>
<textarea class="form-control" id="content" name="content">
</textarea >
</div>
</div>
<center>
<button type="submit">search</button>
</center>
</form>
</div>
<table id="posts">
<thead>
<tr>
<th>{{__('main.title')}}</th>
<th>{{__('main.post_category')}}</th>
<th>{{__('main.content')}}</th>
</tr>
</thead>
<tbody>
#foreach($details as $detailkey => $detail)
<tr>
<td>{{$detail->title}}</td>
<td>{{$detail->category->cat_name}}</td>
<td>{{$detail->content}}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
Controller
public function index()
{
$ctegories= Category::all();
return view('search')->with('posts', Post::all())->with('ctegories', $ctegories);
}
public function searchresult(Request $request)
{
$title= $request->title;
$content= $request->content;
$cat_id= $request->cat_id;
$posts= Post::where('title', 'like', '%' . $title. '%')
->whereHas('category', function(Builder $query) use ($sujet_id){
$query->where('id', $cat_id);
})
->orderBy('created_at','desc')
->get();
//for form dropdown categories
$categories= Category::all();
if(count ($posts) > 0)
{
//this what i want to change from view to route with those parameters
return view('searchresult')
->withDetails($posts)->withQuery($title)
->withCategories($categories);
} else {
return redirect()->route('index')->with('success','search not found');
}
}
So otherwise the function works perfectly and I get the data
i will appreciate your help thank you
You should use below method to return route with parameters:
return \Redirect::route('nameOfRoute', ['param1'=>'value1','param2'=>'value2',...])->with('message', 'Search found!!!');

Laravel - How to apply Laravel old() helper function on dynamic input form

In Laravel-5.8 project, I am working on dynamic input form.
The main model is AppraisalGoal while the second model is AppraisalGoalDetail
Controller
public function create()
{
$goal = new AppraisalGoal();
$goaldetail = new AppraisalGoalDetail();
return view('appraisal.appraisal_goals.create')
->with('goal', $goal)
->with('goaldetail', $goaldetail) ;
}
public function store(StoreAppraisalGoalRequest $request)
{
DB::beginTransaction();
try {
$goal = new AppraisalGoal();
$goal->weighted_score = $request->weighted_score;
$goal->goal_title = $request->goal_title;
$goal->goal_description = $request->goal_description;
if ($request->appraisal_doc != "") {
$appraisal_doc = $request->file('appraisal_doc');
$new_name = rand() . '.' . $appraisal_doc->getClientOriginalExtension();
$appraisal_doc->move(public_path('storage/documents/appraisal_goal'), $new_name);
$goal->appraisal_doc = $new_name;
}
$goal->save();
foreach ( $request->activity as $key => $activity){
$startDate = Carbon::parse($request->start_date[$key]);
$endDate = Carbon::parse($request->end_date[$key]);
$insert_array = [
'kpi_description' => $request->kpi_description[$key],
'activity' => $request->activity[$key],
'start_date' => $startDate ->toDateTimeString(),
'end_date' => $endDate->toDateTimeString(),
];
AppraisalGoalDetail::create($insert_array );
}
DB::commit();
Session::flash('success', 'Goal is created successfully');
return redirect()->route(goals.index');
} catch (Exception $exception) {
DB::rollback();
Session::flash('error', 'Action failed! Please try again');
return redirect()->route('goals.index');
}
}
the create.blade view is shown below
<form action="{{route('goals.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-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" value="{{ old('goal_title', $goal->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" value="{{old('goal_description',$goal->goal_description)}}" placeholder="Enter Goal Description here ...">{{old('goal_description',$goal->goal_description)}}</textarea>
</div>
</div>
<div class="col-sm-12">
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">Activity<span style="color:red;">*</span></th>
<th scope="col">KPI<span style="color:red;">*</span></th>
<th scope="col">Start Date<span style="color:red;">*</span></th>
<th scope="col">End Date<span style="color:red;">*</span></th>
<th scope="col"><a class="btn btn-info addRow"><i class="fa fa-plus"></i></a></th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="activity[]" class="form-control activity" ></td>
<td><input type="text" name="kpi_description[]" class="form-control kpi_description" ></td>
<td><input type="date" class="form-control start_date" placeholder="dd/mm/yyyy" name="start_date[]" min="{{Carbon\Carbon::now()->firstOfYear()->format('Y-m-d')}}" max="{{Carbon\Carbon::now()->lastOfYear()->format('Y-m-d')}}"></td>
<td><input type="date" class="form-control end_date" placeholder="dd/mm/yyyy" name="end_date[]" min="{{Carbon\Carbon::now()->firstOfYear()->format('Y-m-d')}}" max="{{Carbon\Carbon::now()->lastOfYear()->format('Y-m-d')}}"></td>
<td><a class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>
</tr>
</tbody>
</table>
</div>
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Weight(%):<span style="color:red;">*</span></label>
<input type="number" name="weighted_score" placeholder="Enter weighted score here" class="form-control" max="120">
</div>
</div>
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Attachment:</label>
<div class="custom-file">
<input value="{{old('appraisal_doc',$goal->appraisal_doc)}}" type="file" name="appraisal_doc" class="custom-file-input" id="customFile">
<label class="custom-file-label" for="exampleInputFile">Choose file</label>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
</div>
</form>
AppraisalGoal is foreignkey to AppraisalGoalDetail. AppraisalGoalDetail is an Array.
The way the application operates is that, When the user clicks the submit button, the application saves into AppraisalGoal and pick its id and saves it with the other data into AppraisalGoalDetail.
However, the validation is giving issue. Whenever the user submits and the page is validated, all went blank upon showing the error page, meaning that I need to input them all over again.
I was able to resolve these ones that belong to AppraisalGoal model by using old() help function and it works:
<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" value="{{ old('goal_title', $goal->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" value="{{old('goal_description',$goal->goal_description)}}" placeholder="Enter Goal Description here ...">{{old('goal_description',$goal->goal_description)}}</textarea>
</div>
</div>
I don't know how to resolve these ones that belong to AppraisalGoalDetail:
<tr>
<td><input type="text" name="activity[]" class="form-control activity" ></td>
<td><input type="text" name="kpi_description[]" class="form-control kpi_description" ></td>
<td><input type="date" class="form-control start_date" placeholder="dd/mm/yyyy" name="start_date[]" min="{{Carbon\Carbon::now()->firstOfYear()->format('Y-m-d')}}" max="{{Carbon\Carbon::now()->lastOfYear()->format('Y-m-d')}}"></td>
<td><input type="date" class="form-control end_date" placeholder="dd/mm/yyyy" name="end_date[]" min="{{Carbon\Carbon::now()->firstOfYear()->format('Y-m-d')}}" max="{{Carbon\Carbon::now()->lastOfYear()->format('Y-m-d')}}"></td>
<td><a class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>
</tr>
How do I get this corrected that the page should still retain the data after submit and validation error?
Thank you
When You get Validation Error & something fault in server..You redirect the page & withInput() function like this..
return redirect()->route('goals.index')->withInput(['goal_title' => $request->goal_title, 'goal_description' => $request->goal_description]);
It will sork & show your value which you give to update

Laravel - How to validate fields from another tables in Request Rules

Using Laravel-5.8, I am trying to delevop a web application.I have two tables: goals and goal_details. Goal is the main model class.
Using Rules and Request in Laravel:
public function rules()
{
return [
'goal_title' => 'required|min:5|max:100',
'goal_type_id' => 'required',
'weighted_score' => 'required|numeric|min:0|max:500',
'start_date' => 'required',
'end_date' => 'required|after_or_equal:start_date',
'kpi_description' => 'required',
'activity' => 'required',
];
}
goals: customer_id, goal_title, weighted_score, start_date, end_date
goal_details: goal_type_id, kpi_description
public function create()
{
$userCompany = Auth::user()->company_id;
$identities = DB::table('appraisal_identity')->select('id','appraisal_name')->where('company_id', $userCompany)->where('is_current', 1)->first();
$goaltypes = GoalType::where('company_id', $userCompany)->get();
$categories = GoalType::with('children')->where('company_id', $userCompany)->whereNull('parent_id')->get();
return view('goals.create')
->with('goaltypes', $goaltypes)
->with('categories', $categories)
->with('identities', $identities);
}
public function store(StoreGoalRequest $request)
{
$startDate = Carbon::parse($request->start_date);
$endDate = Carbon::parse($request->end_date);
$userCompany = Auth::user()->company_id;
$employeeId = Auth::user()->employee_id;
$goal = new Goal();
$goal->goal_type_id = $request->goal_type_id;
$goal->appraisal_identity_id = $request->appraisal_identity_id;
$goal->employee_id = $employeeId;
$goal->weighted_score = $request->weighted_score;
$goal->goal_title = $request->goal_title;
$goal->goal_description = $request->goal_description;
$goal->start_date = $startDate;
$goal->end_date = $endDate;
$goal->save();
foreach ( $request->activity as $key => $activity){
$goaldetail = new GoalDetail();
$goaldetail->kpi_description = $request->kpi_description[$key];
$goaldetail->activity = $request->activity[$key];
$goaldetail->appraisal_goal_id = $goal->id;
$goaldetail->save();
}
Session::flash('success', 'Goal is created successfully');
return redirect()->route('goals.index');
}
create.blade.php
<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-sm-12">
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">Activity<span style="color:red;">*</span></th>
<th scope="col">KPI Description<span style="color:red;">*</span></th>
<th scope="col">Attachment</th>
<th scope="col"><a class="addRow"><i class="fa fa-plus"></i></a></th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="activity[]" class="form-control activity" ></td>
<td><input type="text" name="kpi_description[]" class="form-control kpi" ></td>
<td>
<div class="custom-file">
<input type="file" name="appraisal_doc[]" class="custom-file-input" id="customFile">
<label class="custom-file-label" for="exampleInputFile">Choose file</label>
</div>
</td>
<td><a class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>
</tr>
</tbody>
</table>
</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 class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Start Date:<span style="color:red;">*</span></label>
<input type="date" class="form-control" placeholder="dd/mm/yyyy" name="start_date" min="{{Carbon\Carbon::now()->format('Y-m-d')}}">
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> End Date:<span style="color:red;">*</span></label>
<input type="date" class="form-control" placeholder="dd/mm/yyyy" name="end_date" min="{{Carbon\Carbon::now()->format('Y-m-d')}}">
</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('appraisal.appraisal_goals.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
</div>
<!-- /.card -->
</div>
<!--/.col (left) -->
</div>
javascript
<script type="text/javascript">
$(document).ready(function(){
$('.addRow').on('click', function () {
var isHod = {{ Auth::user()->is_hod == 0 ? 0 : 1 }};
var numRows = $('.activity').length
if (isHod || (!isHod && numRows<3)) {
addRow();
}
});
function addRow() {
var addRow = '<tr>\n' +
' <td><input type="text" name="activity[]" class="form-control activity" ></td>\n' +
' <td><input type="text" name="kpi_description[]" class="form-control kpi_description" ></td>\n' +
' <td><div class="custom-file"><input type="file" name="appraisal_doc[]" class="custom-file-input" id="customFile"><label class="custom-file-label" for="exampleInputFile">Choose file</label></div></td>\n' +
' <td><a class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>\n' +
' </tr>';
$('tbody').append(addRow);
addRemoveListener();
};
addRemoveListener();
});
function addRemoveListener() {
$('.remove').on('click', function () {
var l =$('tbody tr').length;
if(l==1){
alert('you cant delete last one')
}else{
$(this).parent().parent().remove();
}
});
}
</script>
When I submitted, I observed that the fields from goal_details: goal_type_id, kpi_description are not validated as required. It allows null. But all fields in goals are validated.
How do I resolve this?
Thank you.
Check if it can solve your "kpi_description" validation problem :
public function rules()
{
return [
'goal_title' => 'required|min:5|max:100',
'goal_type_id' => 'required',
'weighted_score' => 'required|numeric|min:0|max:500',
'start_date' => 'required',
'end_date' => 'required|after_or_equal:start_date',
'kpi_description' => 'required|array',
'kpi_description.*' => 'required',
'activity' => 'required',
];
}
after defining rules you have to call "validated" method as needed.
try this :
public function store(StoreGoalRequest $request)
{
$validated = $request->validated();
$startDate = Carbon::parse($request->start_date);
$endDate = Carbon::parse($request->end_date);
$userCompany = Auth::user()->company_id;
$employeeId = Auth::user()->employee_id;
$goal = new Goal();
$goal->goal_type_id = $request->goal_type_id;
$goal->appraisal_identity_id = $request->appraisal_identity_id;
$goal->employee_id = $employeeId;
$goal->weighted_score = $request->weighted_score;
$goal->goal_title = $request->goal_title;
$goal->goal_description = $request->goal_description;
$goal->start_date = $startDate;
$goal->end_date = $endDate;
$goal->save();
foreach ( $request->activity as $key => $activity){
$goaldetail = new GoalDetail();
$goaldetail->kpi_description = $request->kpi_description[$key];
$goaldetail->activity = $request->activity[$key];
$goaldetail->appraisal_goal_id = $goal->id;
$goaldetail->save();
}
Session::flash('success', 'Goal is created successfully');
return redirect()->route('goals.index');
}

Laravel Error during update - Undefined variable: id

I am working on a project using Laravel-5.8
protected $table = 'ratings';
protected $fillable = [
'rating_type',
'rating_value',
'rating_description',
];
public function rules()
{
return [
'rating_type' => 'required|numeric|min:1|max:10|unique:appraisal_ratings,rating_type,company_id'.$this->id,
];
}
The rating has an id column, and that's the primary key. Why I checked it against company_id is that different companies can have the same rating type.
Controller
public function edit($id)
{
$rating = Rating::where('id', $id)->first();
return view('ratings.edit')
->with('rating', $rating)
->with('rating_types', $this->rating_types)
->with('rating_descriptions', $this->rating_descriptions)
->with('rating_values', $this->rating_values);
}
public function update(UpdateRatingRequest $request, $id)
{
$rating = Rating::find($id);
$rating->rating_type = $request->rating_type;
$rating->rating_value = $request->rating_value;
$rating->rating_description = $request->rating_description;
$rating->save();
Session::flash('success', 'Rating is updated successfully');
return redirect()->route('ratings.index');
}
edit.blade
<form action="{{route('ratings.update', ['id'=>$rating->id])}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{ csrf_field() }}
<input name="_method" type="hidden" value="PUT">
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Rating:<span style="color:red;">*</span></label>
<select class="form-control select2bs4" data-placeholder="Choose Rating" tabindex="1" name="rating_type" style="width: 100%;">
<option value="">Select Rating</option>
#foreach($rating_types as $k => $rating_type)
<option value="{{$k}}" #if($rating->rating_type == $k) selected #endif>{{$rating_type}}</option>
#endforeach
</select>
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Description:<span style="color:red;">*</span></label>
<select class="form-control select2bs4" data-placeholder="Choose Description" tabindex="1" name="rating_description" style="width: 100%;">
<option value="">Select Description</option>
#foreach($rating_descriptions as $k => $rating_description)
<option value="{{$k}}" #if($rating->rating_description == $k) selected #endif>{{$rating_description}}</option>
#endforeach
</select>
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Rating Score:<span style="color:red;">*</span></label>
<select class="form-control select2bs4" data-placeholder="Choose Rating Score" tabindex="1" name="rating_value" style="width: 100%;">
<option value="">Select Rating Score</option>
#foreach($rating_values as $k => $rating_value)
<option value="{{$k}}" #if($rating->rating_value == $k) selected #endif>{{$rating_value}}</option>
#endforeach
</select>
</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('ratings.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
When I clicked on the save button to update, I got this error:
rating_type already exists.
That error should not have occured since I am doing update.
How do I resolve it?
Thank you.
You are checking the unique on update wrong
Unique Rule Usage
unique:table,column,except,idColumn
* 3rd param is for value for column to except and 4th is for column to except
Fix
//App\Http\Requests\UpdateRatingRequest
'rating_type' => 'required|numeric|min:1|max:10|unique:table_name,rating_type,table_primary_key'.$this->id,

Laravel Request Input is not usable data

Ok maybe this is a noob laravel question but when I'm trying to store data from a form I used a $request->input in a query to get a needed field for insert but the query will not run. Note: does run if I just set something like $project_id = 6.
public function store(Request $request)
{
$project_id = $request->input('project_id');
$company = Project::where('id', $project_id)->first();
if(Auth::check()){
$task = Task::create([
'name' => $request->input('name'),
'project_id' => $project_id,
'company_id' => $company->id,
'days' => $request->input('days'),
'hours' => $request->input('hours'),
'user_id' => Auth::user()->id
]);
if($task){
return redirect()->route('tasks.index')
->with('success' , 'Task created successfully');
}
}
return back()->withInput()->with('errors', 'Error creating new task');
}
Note:
I've tried a couple different things I've found online like $project_id = $request->project_id or $project_id = $request['project_id']
Is request->input just used for inserts and can't be used as a normal varible?
Update: here is the create.blade form it's coming from
#extends('layouts.app')
#section('content')
<div class="row col-md-9 col-lg-9 col-sm-9 pull-left " >
<h1>Add a Task </h1>
<!-- Example row of columns -->
<div class="col-md-12 col-lg-12 col-sm-12" style="background: white; margin: 10px;" >
<form method="post" action="{{ route('tasks.store') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="project-name">Name<span class="required">*</span></label>
<input placeholder="Enter name"
id="project-name"
required
name="name"
spellcheck="false"
class="form-control"
/>
</div>
<div class="form-group">
<label for="task-days">Days Taken<span class="required"></span></label>
<input
id="task-days"
required
name="days"
type="number"
spellcheck="false"
class="form-control"
/>
</div>
<div class="form-group">
<label for="task-hours">Hours Taken<span class="required"></span></label>
<input
id="task-hours"
required
name="hours"
type="number"
spellcheck="false"
class="form-control"
/>
</div>
<input
class="form-control"
type="hidden"
name="project_id"
value="{{ $project_id }}"
/>
#if($projects != null)
<div class="form-group">
<label for="company-content">Select Project</label>
<select name="project_id" class="form-control">
#foreach($projects as $project)
<option value="{{$project_id}}">{{ $project->name }}</option>
#endforeach
</select>
</div>
#endif
<div class="form-group">
<input type="submit" class="btn btn-primary"
value="Submit"/>
</div>
</form>
</div>
</div>
<div class="col-sm-3 col-md-3 col-lg-3 col-sm-3 pull-right">
<div class="sidebar-module sidebar-module-inset">
<h4>Actions</h4>
<ol class="list-unstyled">
<li>All tasks</li>
</ol>
</div>
</div>
#endsection
Let's examine your <form> below:
<input class="form-control" type="hidden" name="project_id" value="{{ $project_id }}"/>
#if($projects != null)
<div class="form-group">
<label for="company-content">Select Project</label>
<select name="project_id" class="form-control">
#foreach($projects as $project)
<option value="{{ $project_id }}">{{ $project->name }}</option>
#endforeach
</select>
</div>
#endif
In this code, you have a hidden input with the name "project_id", and if $projects is not null, you also have a select with the name "project_id". Having multiple elements with the same name is invalid, and can cause issues.
Secondly, in this line:
<option value="{{ $project_id }}">{{ $project->name }}</option>
$project_id is the same value you have in the hidden input above. When you're looping over $projects, this should be $project->id:
<option value="{{ $project->id }}">{{ $project->name }}</option>
Lastly, make sure that $project_id is a valid value if you're going to send it, and consider adjusting your logic to only send the hidden input if $projects is null:
#if($projects != null)
<div class="form-group">
<label for="company-content">Select Project</label>
<select name="project_id" class="form-control">
#foreach($projects as $project)
<option value="{{ $project->id }}">{{ $project->name }}</option>
#endforeach
</select>
</div>
#else
<input class="form-control" type="hidden" name="project_id" value="{{ $project_id }}"/>
#endif
With all that adjusted, you should be able to retrieve the expected value with $request->input("project_id")

Resources