storing array in database when checkbox is not checked - laravel

Im using Laravel 7 and trying to save opening hours to database.
Im using checkbox and time fields for each day of week. If all the days are selected, it stores to database with no problem. If the day is not checked It doesn't store the dayi. i need it to be saved inactive.
here is my view and controller files. What am i doing wrong here??
<td>
<div class=" weekDays-selector">
<input type="checkbox" id="day-mon" class="weekday" name="day[]" value="1" #if($days['0']->status == 'active') checked #endif />
<label for="day-mon">Monday </label>
</div>
</td>
<td>
<div class="input-group clockpicker" data-autoclose="true" #if($days['0']->status == 'inactive') style="display: none" #endif id="mon-from">
<span class="input-group-addon">
<span class="fa fa-clock-o"></span>
</span><input type="text" class="form-control" placeholder="09:00" name="from[]" autocomplete="off" value="{{\Carbon\Carbon::createFromFormat('H:i:s',$days['0']->from)->format('G:i')}}">
</div>
</td>
Controller
$from = $request->from;
$to = $request->to;
$day = $request->day;
for( $count = 0; $count < 7; $count++ )
{
$newday = new Day;
$newday->vendor_id = $setting->id;
$newday->day = $count+1;
$newday->from = $request->day[$count] ? $from[$count] : '00:00:00';
$newday->to = $request->day[$count] ? $to[$count] : '00:00:00';
$newday->status = $request->day[$count] ? 'active' : 'inactive';
$newday->save();

Related

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

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

Laravel : save radio group with difference key

I want to save radios group in database with different question_id
I tried to use form with radio's input have name=answer
controller :
public function store(Request $request, Survey $survey)
{
$question = \App\Question::where('survey_id', '=' , $survey->id)->get();
$request->validate([
'answer'=>'required'
]);
$arr = $request->except('_token');
$newAnswer = new Answer();
$newAnswer->answer = request()->get('answer');
foreach ($survey->questions as $key=>$question){
$newAnswer->question_id = $question->id;
}
$newAnswer->user_id = Auth::id();
$newAnswer->last_ip = request()->ip();
$newAnswer->survey_id = $survey->id;
$newAnswer->commentaire = request()->get('commentaire');
givePoint(new VoteAdded($newAnswer));
$newAnswer->save();
return redirect()->action('SurveyController#view_survey_answers', [$survey->id]);
}
view :
<div id="Create" class="col-12" style="display:none;">
{!! Form::open(array('action'=>array('AnswerController#store', $survey->id))) !!}
<div class="text-center">
<img class="rounded"
src="https://interactive-examples.mdn.mozilla.net/media/examples/grapefruit-slice-332-332.jpg"
alt="Grapefruit slice atop a pile of other slices" />
</div>
<hr>
#foreach ($survey->questions as $question)
<p class="flow-text">Question {{ $zero++}} - {{ $question->title }}</p>
#if($question->question_type === 'text')
<div class="form-group" style="margin-left: 20px;">
<div class="input-field col s12">
<input id="answer" type="text" name="answer">
<label for="answer">Answer</label>
</div>
</div>
#elseif($question->question_type === 'textarea')
<div class="form-group" style="margin-left: 20px;">
<div class="input-field col s12">
<textarea id="textarea1" class="materialize-textarea" name="{{ $question->id }}[answer]"></textarea>
<label for="textarea1">Textarea</label>
</div>
</div>
#elseif($question->question_type === 'radio')
#foreach($question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
#if($value === 'else')
<div class="form-group" style="margin-left: 20px;">
<input name="answer" class="custom-control-input" type="radio" id="{{ $value }}" value="{{$value}}"/>
<label class="custom-control-label" for="{{ $value }}">{{ $value }}</label>
<div id="textboxes" style="display: none">
<br>
<textarea class="form-control" name="commentaire" id="exampleFormControlTextarea1" rows="3" placeholder="Write a large text here ..."></textarea>
</div>
</div>
#else
<p style="margin:0px; padding:0px;">
<div class="form-group" style="margin-left: 20px;">
<input name="answer[{{$question->id}}]" class="custom-control-input" type="radio" id="{{ $value }}" value="{{ $value}}"/>
<label class="custom-control-label" for="{{ $value }}">{{ $value }}</label>
</div>
</p>
#endif
#endforeach
#elseif($question->question_type === 'checkbox')
#foreach($question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
<div class="form-group">
<input type="checkbox" id="{{ $value }}" name="answer" value="{{$value}}"/>
<label for="{{$value}}">{{ $value }}</label>
</div>
</p>
#endforeach
#endif
<div class="divider" style="margin:10px 10px;"></div>
#endforeach
<div class="form-group">
{{ Form::submit('Submit Survey', array('class'=>'btn btn-success mt-4')) }}
</div>
{!! Form::close() !!}
</div>
Tables :
i have already made it :
Answer table = id, survey_id , question_id , answer . commentaire ,
timestamp
Survey table : id title ...
question table : id , suvey_id , option_type , options
I got in my database a array: ["question_id" = "value"]
what a want is for example i have 2 questions , in my database i want to save 2 row with some survey id but different question id
could you help me to do that ?
-Since 1 survey can have many questions create a separate table for questions like survey_questions
-You can insert in multiple tables at the same time by writing insert queries for the survey and survey questions table separately and wrapping it in a transaction. In Laravel, you can do something like
try{
DB::transaction();
//insert in survey table
//insert in survey questions table
DB::commit();
} catch(\Exception $e){
DB::rollback()
}

Editing user info using laravel

I've built a cms interface for the admin in my website. among other things the admin can add\edit users info using forms.
when I send the edit form I keep getting this error: Column not found: 1054 Unknown column 'updated_at' in 'field list' which suggests that the DB update is trying to save all of the request indexes (which contains values of columns from other table) and not just the one I'm trying to update.
I've manage to track the problem to one line $user_role->save();.
the lines above that do what their suppose to (finding thr correcct user_role and change its value).
Here is my code
Model
static public function update_user($request, $id){
$image_name = '';
if( !empty($request['profile_image']) && $request->hasFile('profile_image') && $request->file('profile_image')->isValid() ){
$file = $request->file('profile_image');
$image_name = date('Y.m.d.H.i.s') . '-' . $file->getClientOriginalName();
$request->file('profile_image')->move( public_path() . '/images/profile-images/' , $image_name);
$img = Image::make( public_path() . '/images/profile-images/' . $image_name );
$img->resize(370, null, function ($constraint) {
$constraint->aspectRatio();
});
$img->save();
}
$user = self::find($id);
$user->name = $request['name'];
$user->email = $request['email'];
$user->phone = $request['phone'];
if( !empty($request['password']) ){
$user->password = bcrypt($request['password']);
}
if(!empty($image_name)){
$user->profile_image = $image_name;
}
if( !empty($request['role_id']) ){
$user_role = Users_role::find($id);
$user_role->role_id = $request['role_id'];
$user_role->save();
}
$user->save();
Session::flash('sm', 'Your profile has been updated');
Session::flash('sm-position', 'toast-top-center');
Session::put('user_name', $request['name']);
}
View
<div class="row">
<div class="span9">
<div class="content">
<div class="module message">
<div class="module-head">
<h3><b>Edit Product</b></h3>
</div><br>
<div class="content">
<div class="module message">
<div class="module-body">
<form action="{{ url('cms/users/' . $user->id) }}" method="POST" novalidate="novalidate" autocomplete="off" enctype="multipart/form-data">
<div class="module-body">
#method('PUT')
#csrf
<input type="hidden" name="user_id" value="{{ $user->id}}">
<div class="form-group">
<div class="input-group mb-3">
<div class="w-100 field-input-cms">
<label for="category-id" class="input-group-text h-50"><span class="text-danger">*</span><b> Permissions:</b></label>
<select name="role_id" class="custom-select span-8">
<option #if ( $user->role_id == 8 ) selected="selected" #endif value="8">Admin</option>
<option #if ( $user->role_id == 2 ) selected="selected" #endif value="2">Regular</option>
</select>
</div>
<small class="text-muted help-text">Please select one option</small><br>
<span class="text-danger"> {{ $errors->first('category_id') }}</span>
</div>
<div class="w-100 field-input-cms">
<label for="name" class="input-group-text h-100"><span class="text-danger">*</span><b> Name:</b></label>
<input type="text" value="{{ $user->name }}" name="name" style="width:100%" class="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-default">
</div>
<small class="text-muted help-text">Name of user</small><br>
<span class="text-danger"> {{ $errors->first('name') }}</span>
<div class="field-input-cms w-100">
<label for="email" class="input-group-text"><span class="text-danger">*</span><b> Email:</b></label>
<input type="text" value="{{ $user->email }}" name="email" size="120" class="form-control mw-100" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-default">
</div>
<small class="text-muted text-balck help-text"> Email of user</small><br>
<span class="text-danger"> {{ $errors->first('email') }}</span>
<div class="field-input-cms w-100">
<label for="phone" class="input-group-text"><span class="text-danger">*</span><b> Phone:</b></label>
<input type="text" value="{{ $user->phone }}" name="phone" size="120" class="form-control mw-100" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-default">
</div>
<small class="text-muted text-balck help-text"> Phone number of user</small><br>
<span class="text-danger"> {{ $errors->first('phone') }}</span>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Upload</span>
</div>
<div class="custom-file">
<input type="file" name="profile_image" class="custom-file-input" id="inputGroupFile01" aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" name="profile_image" for="inputGroupFile01">Choose file</label>
</div>
</div>
<small class="text-muted help-text">Image must be: jpg, jpeg, png, gif. Max: 5mb</small><br>
<span class="text-danger"> {{ $errors->first('profile_image') }}</span>
</div>
<div class="form-group">
<img id="cms-profile-image" src="{{ asset('images/' . $user->profile_image) }}" >
</div><br>
<a class="btn btn-inverse" href="{{ url('cms/users') }}">Cancel</a>
<input type="submit" value="Save Product" name="submit" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
</div>
</div> <!--/.content-->
</div><!--/.span9-->
</div>
Image of the error gaven by laravel
I should mention that if I comment out this code:
if( !empty($request['role_id']) ){
$user_role = Users_role::find($id);
$user_role->role_id = $request['role_id'];
$user_role->update();
}
all the values are saved correctly.
If your users table doesn't have created_at and updated_at columns you should set:
public $timestamps = false;
in your User model.
Laravel by default assumes you have those fields for tables. So whenever record is created/updated it will automatically set/update those fields.
Alternatively you can update your table structure to add those fields and then those fields will be automatically handled by Laravel (in such case don't set timestamps to false).
You might be interested to read about Eloquent conventions

Old Data for Check Box

How Can I get old value for the below check boxes
#if (count($chests) > 0)
#foreach ($chests as $chest)
<br> Day:
#for ($i = 0; $i < $days; $i++)
<label><input type="checkbox" name="{{str_replace(' ', '_', $chest->name)}}_days[]"
value="{{$i+1}}">{{$i+1}}</label>
#endfor
<br>
<label><input type="checkbox" name="chest[]" value="{{$chest->name}}">{{$chest->name}}</label><br>
<div id="div01">
<input type="text" id ="hint" name="{{str_replace(' ', '_', $chest->name)}}_hints[]" placeholder="Hints / Repeats etc">
</div>
#endforeach
#else
No Register Machines
#endif
How I get the old value of checkbox

How to get the data after submit the form based on the form input value using laravel

My controller contain single function with multiple API calling when I returned the controller function to my view api data displayed automatically but i need to display the data while submit the form. Please suggest any solution.
My Controller Code
public function domaincheck(Request $request)
{
ini_set('max_execution_time', 300);
<!-- Domain Availability Check -->
$sld = $request['sld'];
$tld = $request['tld'];
$response = file_get_contents('https://resellertest.enom.com/interface.asp?command=check&sld='. $sld .'&tld='. $tld .'&uid=resellid&pw=resellpw&responsetype=xml');
$data = simplexml_load_string($response);
$configdata = json_encode($data);
$final_data = json_decode($configdata,true);
<!--Domain Name Suggestions -->
$response1 = file_get_contents('http://resellertest.enom.com/interface.asp?command=GETNAMESUGGESTIONS&uid=resellid&pw=resellpw&SearchTerm='. $sld .'&MaxResults=5&ResponseType=XML');
$data1 = simplexml_load_string($response1);
$configdata1 = json_encode($data1);
$final_data1 = json_decode($configdata1,true);
}
My view Code
<form class="form-horizontal" method="get">
<div class="form-group">
<div class=" col-lg-2"></div>
<div class="col-lg-8">
<div class="input-group m-b">
<span class="input-group-addon" style="padding-left:10px; background-color: #999;" class='unclickable'>www</span>
<input type="text" name="sld" class="form-control">
<span class="input-group-addon">
<select class="form-control" name="tld" style="width: 100px;">
<?php $j = 0; ?>
#foreach($final_data2['tldlist']['tld'] as $value)
<?php $j++; ?>
#endforeach
#for ($i = 0; $i < $j-1;)
<option value="{{($final_data2['tldlist']['tld'][$i]['tld'])}}">{{($final_data2['tldlist']['tld'][$i]['tld'])}}</option>
<?php $i++; ?>
#endfor
</select>
</span>
<span class="input-group-addon">
<button type="submit" class="btn btn-sm btn-success">Submit</button>
</span>
</div>
<p class="text-center text-dark customFont" >
#foreach($final_data as $key=>$value)
#if($key=='DomainName')
<b>{{$value}}</b> <b>-</b>
#endif
#if($key=='RRPText')
<b>{{$value}}</b>
#endif
#endforeach
</p>
{{print_r($final_data1)}}
When submit the form (Response) it shows the domain name is available or not available. Response1 is shows the domain name suggestions but it shows the data with out submit the form.Please suggest any solutions

Resources