why Laravel controller doesn't show the zero leading when search from number starts with 0 - laravel

I'm using laravel and I can create a record with barcode = 069, or barcode = 006, however when I
Click the search button, it shows 69 in the form, below view, controller...etc, please I need help:
HTML where i enter value to search:
<div class="container my-container">
<div class="lead text-center font">
<h3><strong><u> Search Form</u></h3></strong>
</div>
<form action="{{ route('store.show')}}" method="GET">
{{ csrf_field() }}
<div class="input-group">
<input type="text" class="form-control" required name="name" placeholder="Scan Barcod">
<span class="input-group-btn">
<button type="submit" class="btn btn-primary" name="submit" value="serach">
<span class="glyphicon glyphicon-search"></span>
</button>
</form>
</div>
Controller: for the same view
public function show()
{
$saved_barcode= request('name');
$searchbyfield = store::find($saved_barcode);
if ($searchbyfield) {
return view('store.show', ['store'=> $searchbyfield]);
}
return redirect('store/create')->with('missing', 'Item not Found');
}
HTML where show the search result
<form action= "{{ route('store.editbarcode',$store -> barcode) }}" method="GET">
{{ csrf_field() }}
<div class="input-group">
<span class="input-group-addon">
<strong>Asset ID </strong></strong>
<span style="color: red">*</span>
</span>
<input disabled type="text" class="form-control" required id="barcode" name="barcode" value="{{ $store -> barcode }}">
<span class="input-group-btn">
<button type="submit" class="btn btn-primary" name="submit" >
<span class="glyphicon glyphicon-edit"></span>
</button>
</form>
</div>

This is most probably because you are saving barcode value in integer type column.
To allow your database engine store leading zeros, you should change the column type to varchar or string as in Laravel. It will solve your problem.

Assuming the Store has barcode as a string, you could pass the search input as a string instead of int, cuase when you pass it to ->find() it gets casted as int
What you can do is in your controller:
public function show()
{
$saved_barcode= request('name');
$searchbyfield = store::where('barcode', $saved_barcode)->first();
if ($searchbyfield) {
return view('store.show', ['store'=> $searchbyfield]);
}
return redirect('store/create')->with('missing', 'Item not Found');
}
EDIT
After reading what you said, perhaps you would wanna set this value in your Store model:
protected $primaryKey = 'barcode';
public $incrementing = false;
protected $keyType = 'string';

Related

How to use laravel redirect back with compact

I am trying to pass value from the price page via input and redirect back to the price page with a value that has been calculated. I am using two functions for this; one is for get price()-PagesController#pricing and the other one is for post feeCal()-PagesController#feeCal.
public function pricing(Request $request)
{
return response()->view('pages.price');
}
public function feeCal(Request $request)
{
$value = $request->input('price');
if ($value > 500 or $value > 20000) {
$fee = $value * 0.015;
}
// dd($fee);
return redirect()->back()->compact('fee');
}
<form action="{{ route('page.vfee')}}" method="POST">
#csrf
<div class="row">
<input type="number" name="price" class="form-control rounded mb-3" placeholder="Type the price here">
</div>
<div class="row">
<input type="submit" class="btn btn-danger w-100
rounded" value="GET TOTAL FEE">
</div>
</form>
<div class="card-footer">
<div class="text-muted">Total fee</div>
<div class="text-danger">
{{ $fee ?? '' }}
</div>
</div>
When you try to input a value it returns a black value but when you dump the fee variable in the controller function you get a result.
Try one of following
return redirect()->back()->with(compact('fee'));
or
return redirect()->back()->with('fee', $fee);

Laravel 7- Pass database value or a value stored in a variable, to Laravel Blade

I am trying to obtain value from database and pass it to blade. If there is no value in database, a random number is generated and passed from the controller. However, I am unable to fetch the value even if it exists. I am getting 1 for every value available in database
Here are my codes
Controller
public function new_user2(Request $request){
if(!Auth::check()){
$reference = $request->refno;
if((is_null($reference))){
$ref1 = mt_rand(10,1000);
$ref2 = mt_rand();
$reference = $ref1."-".$ref2;
} else{
$tuser = DB::table('temp_users')->where('referenceno',$reference)->first();
if(is_null($tuser)){
return redirect()->back()->with('error',"Invalid Reference No. Please enter a valid one");
}else{
// return view('multipage1',compact('tuser'));
return view('multipage1',compact('tuser'));
}
}
return view('multipage1')->with('ref',$reference);
}else{
Auth::login();
}
}
Blade
<div class="body1">
<div class="container container2">
<div class="row">
<div class="col-md-8 offset-md-2">
<h1 class="text-white text-center display-2">Step 1</h1>
<div class="login-form">
<form id="newuser2_step1" action="{{url('mpage2')}}" method="post" autocomplete="off">
#csrf
<div class="form-group">
<label for="RefNo">Reference Number: </label>
<input type="text" class="form-control" id="refno" name="refno" value="{{$tuser->referenceno or $ref}}" readonly><br>
</div>
<div class="form-group">
<!-- Alert Message -->
<div class="alert alert-danger " role="alert" id="alerts">
<strong id="emailtaken"></strong>
</div>
<label for="exampleInputEmail1">Email address</label>
<input type="text" class="form-control" id="email" name="email" placeholder="Enter email" value="{{$tuser->temp_email or ''}}">
<div class="error text-danger" ></div>
</div>
<button type="submit" class="btn btn2 btn-primary" id="mstep1">Get Started</button>
</form>
</div>
</div>
</div>
</div>
</div>
Database table
Data exists in referenceno and temp_email columns
Output in Browser
According to this article, the Laravel or operator that you used, is discontinued. So, use null coalesce operator instead.
value="{{$tuser->referenceno ?? $ref}}"
Similarly, replace the email value with similar coede
You have change this type of statements {{$tuser->referenceno or $ref}}
It is basically checking true/false that why you are getting 1.
Do something like this {{ isset($tuser->referenceno) ? $tuser->referenceno : $ref}}

I got error this Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, integer given, called in

I am trying to update my record but unfortunately record is not updating i getting error please help me thanks.
Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, integer given, called in /home/zubair/htdocs/hourlog/cms/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar.php on line 869
https://flareapp.io/share/q5YBBDmX
Controller
public function issuesUpdate(Request $request,Project $project)
{
$project_id =$project->id;
foreach($request->date as $key =>$value){
$issue = new Issue();
$issue->date = $request->date[$key];
$issue->issue = $request->issue[$key];
$issue->project_id = $project_id ;
$issue->save();
}
return redirect()->route('project');
}
html view
#foreach($issues as $key=>$details)
<div class="row">
<div class="col-md-5">
<div class="form-group">
<input required type="date" value="{{$details->date}}" name="date[{{$key}}][]" class="form-control"
aria-describedby="emailHelp" >
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<input required type="text" value="{{$details->issue}}" name="issue[{{$key}}][]" class="form-control"
aria-describedby="emailHelp" placeholder="task...">
</div>
</div>
<div class="col-md-1 mt12">
<button type="button" class="btn btn-danger waves-effect
waves-light btn-sm delete">
<i
class="fa fa-times">
</i>
</button>
</div>
</div>
#endforeach
Route
Route::post('/projects/{project}/issues/update',
"ProjectController#issuesUpdate")->name('project.issues.update');
maybe this will help you try it
public function issuesUpdate(Request $request,Project $project)
{
$project_id =$project->id;
$dates = $request->get('date');
foreach($dates as $key =>$value){
$issue = new Issue();
$issue->date = $request->get('date');
$issue->issue = $request->get('issue');
$issue->project_id = $project_id ;
$issue->save();
}
return redirect()->route('project');
}

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 5 session()->keep method not working

I have a view with an input date field and a table beneath that. The table is populated based on the date entered. When the date is entered I use a POST method on the form which handles the DB request and returns the same view with the data. I'd like to also return the original date that was entered. I tried session()->keep and flashOnly methods. None return the input date to the view.
My controller:
public function groupTestAthletes(Request $request)
{
$inputDate = null;
$tests = null;
if ($request['tgroupdate']){
$inputDate = Carbon::createFromFormat('d/m/Y', $request['tgroupdate']);
$tests = Test::where('test_date', '=', $inputDate->format('Y-m-d'))
->orderBy('athlete_id', 'desc')
->get();
}
$request->session()->keep(['tgroupdate']);
//$request->flashOnly(['tgroupdate']);
return view('npr.test_athletes', ['tests' => $tests]);
My view:
<form class="form-inline" role="form" method="POST" action="{{ route('admin.search_tgroup') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="tgroupdate" class="control-label">Test Date</label>
<div class="input-group date" id="testgroupdatepicker">
<input name="tgroupdate" type="text" style="background-color:#ffffff" readonly=""
value="{{ Session::get('tgroupdate') }}" class="form-control">
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Search Athletes
</button>
<input type="hidden" name="_token" value="{{ Session::token()}}">
</div>
</form>
You dont need to save the date in session. You can save the date in a variable,send it to the view and in the view you can check if variable exist using isset php function.
In Controller
public function groupTestAthletes(Request $request)
{
$inputDate = null;
$tests = null;
if ($request['tgroupdate']){
$inputDate = Carbon::createFromFormat('d/m/Y', $request['tgroupdate']);
$tests = Test::where('test_date', '=', $inputDate->format('Y- m-d'))
->orderBy('athlete_id', 'desc')
->get();
}
return view('npr.test_athletes', ['tests' => $tests,'selected_date' => $request['tgroupdate']]);
And in the view,
<form class="form-inline" role="form" method="POST" action="{{ route('admin.search_tgroup') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="tgroupdate" class="control-label">Test Date</label>
<div class="input-group date" id="testgroupdatepicker">
<input name="tgroupdate" type="text" style="background-color:#ffffff" readonly=""
value="#if(isset($selected_date)) $selected_date #endif" class="form-control">
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Search Athletes
</button>
<input type="hidden" name="_token" value="{{ Session::token()}}">
</div>
</form>
Edit: This minor change in the view gave the optimal solution.
value="#if(isset($selected_date)){{$selected_date}}#endif"

Resources