$request->input returns null laravel 8 - php

I have a form with 3 fields - start date, end date and pattern. I want to pick the values from the input and check if those are empty. if not then compare the dates and perform action. By when I tried passing the value `$request->input('from')` in $status, it returned null.
my form:
<div class="modal-body">
<form action="App\Http\Controllers\HolidayController#addSchedule" method="POST" autocomplete="off" id="scheduleForm">
#include('partials.holidayFormModal')
</form>
</div>
holidayFormModal:
<link rel="stylesheet" href="{{ url('assets/custom/css/schedule/scheduleForm.css') }}">
<div class="form-group row col-md-12 date-picker">
<label class="col-sm-2 date-picker-label" for="from">
{{ __('messages.schedule_period') }}
</label>
<div class="input-group col-sm-4">
<input class="form-control" id="start_datepicker" type="text" name="from" autocomplete="off" readonly>
<span class="input-group-addon">
<i class="fas fa-calendar-alt"></i>
</span>
</div>
<div class="col-sm-2"></div>
<div class="input-group col-sm-4">
<input class="form-control" id="end_datepicker" type="text" name="to" autocomplete="off" readonly>
<span class="input-group-addon">
<i class="fas fa-calendar-alt"></i>
</span>
</div>
</div>
<div class="form-group row col-md-12 motif-picker">
<label class="col-sm-2 motif-label" for="meotif">
{{ __('messages.schedule_motif') }}
</label>
<input class="form-control col-sm-10" type="text" id="motif" name="motif" max="60">
</div>
<div class="col-md-11"></div>
<div class="col-md-1" id="schedule-submit">
<button class="btn" type="button" id="schedule_form_submit_button">
<i class="fas fa-check-circle fa-3x"></i>
</button>
</div>
web.php :
Route::get('/holidays', ['uses' => $controllerNamespace . 'HolidayController#index', 'as' => 'holidays']);
Route::post('/holidayAdd',['uses' => $controllerNamespace . 'HolidayController#addSchedule', 'as' => 'holidayAdd']);
HolidayController:
public function addSchedule(Request $request) {
$scheduleModelObj = new ScheduleModel;
$scheduleModelObj->from = $request->from;
$scheduleModelObj->to = $request->to;
$scheduleModelObj->motif = $request->motif;
$fromDate = str_replace('/', '-', $request->from);
$toDate = str_replace('/', '-', $request->to);
$f = date('Y-m-d', strtotime($fromDate));
$t = date('Y-m-d', strtotime($toDate));
if ($f == '' || $t == '' || $scheduleModelObj->motif == '') {
$returnMessage['date'] = __('messages.schedule_end_date_error');
$returnMessage['motif'] = __('messages.schedule_motif_error');
$status = 'error';
} else {
if ($f < $t) {
$scheduleModelObj->searchSchedule($scheduleModelObj->from, $scheduleModelObj->to);
$status = 'success';
}
$returnMessage['date'] = __('messages.schedule_end_date_error');
$returnMessage['motif'] = __('messages.schedule_motif_error');
$status = 'error';
}
return ['status' => $status, 'message' => $returnMessage];
}

Try this:
<div class="modal-body">
<form action="{{route('holidayAdd')}}" method="POST" autocomplete="off" id="scheduleForm">
#include('partials.holidayFormModal')
</form>
</div>

Related

Error when input date on laravel 5.4

I am using Laravel to create a project but I get some issue when creating a form that uses date:
Is there something missing in the table or script?
Here the table
Here the controller
public function index(Request $request){
$data = array();
if($request->isMethod('post') == "post"){
$pendaftar = new PendaftarModel();
$pendaftar->tgl =$request->input(['date']);
$pendaftar->nopol =$request->input('no polisi');
$pendaftar->motor =$request->input('jenis service');
$pendaftar->servis =$request->input('keluhan kendaraan');
$pendaftar->keluhan =$request->input('keluhan kendaraan');
// $pendaftar->keluhan =$request->input('keluhan kendaraan');
if($pendaftar->save()){
$data["status"] = "success";
$data["message"] = "Selamat, booking berhasil. Staff kami akan segera menghubungi anda untuk penjadwalan";
}else {
$data["status"] = "danger";
$data["message"] = "Maaf, Booking Gagal";
}
}
return view("daftar", $data);
The view blade
div class="well well-lg">
<div class="container">
<h2>Booking Online</h2>
<span>Halaman untuk melakukan pendaftaran kendaraan.</span>
</div>
</div>
<div class="container">
<div class="alert alert-info">
<i class="glyphicon glyphicon-info-sign"></i> Silahkan isi data berikut
</div>
<div class="panel panel-primary">
<div class="panel-heading">
Form Data Kendaraan
</div>
<div class="panel-body">
#if(isset($status))
<div class="alert alert-<?php echo $status; ?>">
<?php echo $message; ?>
</div>
#endif
<form method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="tanggal">Pilih Tanggal</label>
<input class="form-control" id="tanggal" required type="date" name="tgl" max="3000-12-31"
min="1000-01-01" placeholder="Pilih Tanggal">
</div>
<div class="form-group">
<label for="nopol">Nomor Polisi:</label>
<input class="form-control" id="nopol" required type="text" name="nopol" placeholder="Masukkan No Polisi">
</div>
<div class="form-group">
<label for="motor">Jenis Motor:</label>
<input class="form-control" id="motor" required type="text" name="motor" placeholder="Matic/Bebek/Sport">
</div>
<div class="form-group">
<label for="servis">Tipe Service:</label>
<input class="form-control" id="servis" required type="text" name="servis" placeholder="Besar/Kecils">
</div>
<div class="form-group">
<label for="keluhan">Keluhan Kendaraan:</label>
<textarea name="keluhan" id="keluhan" required class="form-control" rows="5" placeholder="Tulis Keluhan Motor Anda"></textarea>
</div>
<button type="submit" name="submit" class="btn btn-success btn-lg"><i class="glyphicon glyphicon-send"></i> Submit</button>
<button type="reset" class="btn btn-danger btn-lg">Reset</button>
</form>
</div>
</div>
</div>
The Model
{
//
protected $table = "pendaftar";
public $timestamps = true;
protected $fillable=['tgl','nopol','motor','servis','keluhan'];
}
In the snapshot, Your table is missing updated_at column, create a column with the name "updated_at" in your pendafter table.
Another way you can set the model like this:
{
//
protected $table = "pendaftar";
public $timestamps = false; //it should be false
protected $fillable=['tgl','nopol','motor','servis','keluhan'];
}

how to remain value that has been input after redirect back

so I have an if-else function where it will check what is supposed to be in a form, so when I submit the form the function in the controller does the if-else function. So its something like, if there is no value in a hidden input field then it will redirect the user back to the form, but when it does that, all the values for the other text input go missing and a user has to key in all over again. I don't want that to happen. Instead, I want all the other text input to remain. How can I do that?
my blade:
<form id="form-project" role="form" autocomplete="off" action="{{action('Web\TravelController#store')}}" method="POST">
{{csrf_field()}}
<div class="card-bg">
<div class="back-btn">
<a href="{{action('Web\TravelController#index')}}">
<i class="fa fa-angle-left" aria-hidden="true"></i><span>Back</span>
</a>
</div>
<br>
<div class="form-group">
<div class="row">
<div class="col-md-12">
<div class="btn-group">
<a type="button" class="btn tab-btn active btn-tab-lg">Book a trip</a>
<a type="button" class="btn tab-btn btn-tab-lg" href="{{action('Web\TravelController#multiCity')}}">Multi-city</a>
</div>
</div>
</div>
<div class="add-space"></div>
<div class="row">
<div class="col-md-12">
<div class="btn-group">
<label class="btn tab-btn btn-tab-lg">
<input type="radio" name="is_return_trip" class="is_return_trip" value="0" onchange="hideReturn(this)">One-way
</label>
<label class="btn tab-btn active btn-tab-lg">
<input type="radio" name="is_return_trip" class="is_return_trip" value="1" checked onchange="hideReturn(this)">Return
</label>
</div>
</div>
</div>
<div class="extra-padding">
#if(request()->user()->hasRole('PA'))
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Request as</label>
<select class="form-control border-input" name="user_id" required>
<option value="{{$user->id}}">{{$user->name}}</option>
#foreach($user->bosses as $boss)
<option value="{{$boss->id}}">{{$boss->name}}</option>
#endforeach
</select>
<input type="hidden" name="pa_id" value="{{$user->id}}">
<input type="hidden" name="submitted_by_pa">
</div>
</div>
</div>
#else
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="hidden" name="user_id" value="{{$user->id}}">
</div>
</div>
</div>
#endif
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Mode of Transport</label>
<select name="travel_data[transport_type_id]" class="form-control getForm select2" required>
<option value="">Select a transport type</option>
#foreach($transports as $transport)
<option value="{{$transport->id}}">{{$transport->name}}</option>
#endforeach
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<div id="test">
<label>From</label>
<input type="text" class="form-control autocomplete border-input inputDatabaseName" placeholder="From" name="travel_data[from]" required>
<input type="hidden" class="field administrative_area_level_1" disabled="true" name="travel_data[from_state]">
<input type="hidden" class="field country" disabled="true" name="travel_data[from_country]">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div id="test2">
<label>To</label>
<input type="text" class="form-control autocomplete border-input inputDatabaseName2" placeholder="To" name="travel_data[to]" required>
<input type="hidden" class="field administrative_area_level_1" disabled="true" name="travel_data[to_state]">
<input type="hidden" class="field country" disabled="true" name="travel_data[to_country]">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Departure Date</label>
<input type="text" class="form-control datepicker departure-date" placeholder="Departure date" name="travel_data[departure_date]" required>
</div>
</div>
<div class="col-md-6" id="return">
<div class="form-group">
<label>Return Date</label>
<input type="text" class="form-control datepicker return-date" placeholder="Return date" name="travel_data[return_date]">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="button-toggle">
<label>Selected Dates</label>
</div>
<div class="btn-group">
<label class="btn tab-btn active btn-tab-lg" >
<input type="radio" name="travel_data[is_official_date]" class="is_official_date" value="1" checked onchange="showOfficialDates(this)">Official
</label>
<label class="btn tab-btn btn-tab-lg" >
<input type="radio" name="travel_data[is_official_date]" class="is_official_date" value="0" onchange="showOfficialDates(this)">Non-Official
</label>
</div>
</div>
</div>
<div class="row" id="officialdDates" style="display: none;">
<div class="col-lg-12 add-date">
<button class="btn alt-btn-black btn-xs alt-btn dateButton" type="button">
<i class="fa fa-plus"></i>
</button>
</div>
<div class="col-lg-6">
<div class="form-group form-group-default">
<label>From</label>
<input type="text" placeholder="From" class="form-control datepicker fromOfficialDate" name="fromOfficialDate[]">
</div>
</div>
<div class="col-lg-6">
<div class="form-group form-group-default">
<label>To</label>
<input type="text" placeholder="To" class="form-control datepicker toOfficialDate" name="toOfficialDate[]" >
</div>
</div>
</div>
<div class="rulesFormClone"></div>
<br>
<div class="row">
<div class="col-md-12">
<div class="button-toggle">
<label>Accommodation</label>
</div>
<div class="btn-group">
<label class="btn tab-btn active btn-tab-lg" >
<input type="radio" name="travel_data[accommodation]" class="accommodation" value="1" checked>Yes
</label>
<label class="btn tab-btn btn-tab-lg" >
<input type="radio" name="travel_data[accommodation]" class="accommodation" value="0">No
</label>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-md-6">
<div class="form-group">
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Travel Description</label>
<textarea maxlength="500" contentEditable="true" rows="10" cols="50" name="travel_data[description]" class="form-control border-input" placeholder="Travel description" required></textarea>
{{-- <input name="travel_data[description]" type="text" class="form-control border-input" placeholder="Travel Description" required> --}}
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Travel Preferences</label>
<input name="travel_data[travel_preferences]" type="text" class="form-control border-input" placeholder="Travel preferences" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Add Passengers</label>
<input name="travel_data[add_passengers]" type="text" class="form-control border-input" placeholder="Add passengers">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="pull-right" >
<button class="submit-btn" name="status" value='S'>SAVE</button>
<button class="submit-btn text-gold" name="status" value='SB'>SUBMIT</button>
</div>
<div class="clearfix"></div>
<div class="clearfix"></div>
</form>
<div class="row" style="display: none;">
<div class="row datesForm">
<div class="col-lg-12 add-date">
<button class="btn alt-btn-black btn-xs alt-btn dateButton" type="button">
<i class="fa fa-plus"></i>
</button>
</div>
<div class="col-lg-6">
<div class="form-group form-group-default">
<label>From</label>
<input type="text" placeholder="From" class="form-control datepicker fromOfficialDate" name="fromOfficialDate[]">
</div>
</div>
<div class="col-lg-6">
<div class="form-group form-group-default">
<label>To</label>
<input type="text" placeholder="To" class="form-control datepicker toOfficialDate" name="toOfficialDate[]" >
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="card-bg summary-side-bar">
<h4 class="title">Summary</h4>
<h5>Travel Type</h5>
<p class="traveltype">Return</p>
<h5>Travel Route</h5>
<p class="DatabaseName"></p>
<h5>Departure Date</h5>
<p class="departure-date1"></p>
<h5>Return Date</h5>
<p class="return-date1"></p>
</div>
</div>
</div>
</div>
</body>
and my function is:
public function store(Request $request)
{
$user = Auth::user();
$today = date('Y-m-d');
$inputs = $request->all();
$inputTravel_data = $request->input('travel_data');
if($request->has('is_return_trip'))
{
$travelTitle = $inputTravel_data['from'].' - '.$inputTravel_data['to'];
$multiCity = 0;
$is_return_trip = $inputs['is_return_trip'];
}else{
$count = count($inputs['travelLeg']);
$title = $inputTravel_data['from'][0];
for ($i = 1; $i < $count; $i++)
{
$title .= ' - ' . $inputTravel_data['from'][$i];
}
$travelTitle = $title. ' - ' .$inputTravel_data['to'][$count-1];
$multiCity = 1;
$is_return_trip = 0;
}
if(!$inputTravel_data['from_country']){
return redirect()->back();
}else{
if(array_key_exists('id', $inputs) && $inputs['id'])
{
$travel = Travel::where('id',$this->decode($inputs['id']))->first();
if(!$travel)
return $this->error('message','No travel found for this user');
$travel->update([
'status' => $inputs['status'],
'title' => $travelTitle,
'is_multicity' => $multiCity,
'is_return_trip' => $is_return_trip,
'company_id' => $user->company_id,
'submitted_by_pa' => $inputs['user_id'] != Auth::user()->id ? 0 : 1,
'pa_id' => $inputs['user_id'] != Auth::user()->id ? $inputs['pa_id'] : null,
]);
if($inputs['status'] == 'SB' && $inputs['user_id'] == Auth::user()->id){
foreach($travel->travel_data()->where('removed',0)->get() as $t) {
$t->update(['removed'=> 1]);
}
}elseif($inputs['status'] == 'S'){
foreach($travel->travel_data()->where('removed',0)->get() as $t) {
$t->delete();
}
}
if($request->has('is_return_trip'))
{
$travelLeg = new TravelLeg;
$travelLeg->travel_id = $travel->id;
$travelLeg->transport_type_id = $inputTravel_data['transport_type_id'];
$travelLeg->accommodation = $inputTravel_data['accommodation'];
$travelLeg->travel_region_id = $inputTravel_data['travel_region_id'];
$travelLeg->travel_purpose = TravelPurpose::find($inputTravel_data['travel_purpose_id'])->name;
$travelLeg->description = $inputTravel_data['description'];
$travelLeg->travel_prefernces = $inputTravel_data['travel_preferences'];
$travelLeg->add_passengers = $inputTravel_data['add_passengers'];
$travelLeg->from = $inputTravel_data['from'];
$travelLeg->from_state = $inputTravel_data['from_state'] ?? '';
$travelLeg->from_country = $inputTravel_data['from_country'] ?? '';
$travelLeg->to = $inputTravel_data['to'];
$travelLeg->to_state = $inputTravel_data['to_state'] ?? '';
$travelLeg->to_country = $inputTravel_data['to_country'] ?? '';
$travelLeg->departure_date = date('Y-m-d', strtotime(str_replace('/', '-', $inputTravel_data['departure_date'])));
if (!empty($inputTravel_data['return_date']))
{
$travelLeg->return_date = date('Y-m-d', strtotime(str_replace('/', '-', $inputTravel_data['return_date'])));
}
$travelLeg->title = 'Travel Leg 1';
$travelLeg->is_official_date = $inputTravel_data['is_official_date'];
$travelLeg->mode_of_transport = TransportType::find($inputTravel_data['transport_type_id'])->name;
$travelLeg->region = TravelRegion::find($inputTravel_data['travel_region_id'])->name;
$travelLeg->travel_purpose_id = $inputTravel_data['travel_purpose_id'];
$travelLeg->processed = 0;
$travelLeg->save();
if ($travelLeg->is_official_date == self::IS_OFFICIALDATE)
{
$travelLeg->official_date()->delete();
}
if ($travelLeg->is_official_date == self::IS_NOT_OFFICIALDATE)
{
$travelLeg->official_date()->delete();
for ($i = 0; $i < count($inputs['fromOfficialDate']); $i++)
{
$travelDate = new TravelDate;
$travelDate->travel_leg_id = $travelLeg->id;
$travelDate->from = date('Y-m-d', strtotime(str_replace('/', '-', $inputs['fromOfficialDate'][$i])));
$travelDate->to = date('Y-m-d', strtotime(str_replace('/', '-', $inputs['toOfficialDate'][$i])));
$travelDate->save();
}
}
}
else
{
for ($i = 0; $i < $count; $i++)
{
$travelDataFromState ='';
$temporaryIndex = $i;
if ($inputTravel_data['from_state'][$temporaryIndex] == '') {
if (($temporaryIndex-1) <= 0) {
$temporaryIndex = 0;
} else {
$temporaryIndex = $temporaryIndex - 1;
}
$travelDataFromState = $inputTravel_data['to_state'][$temporaryIndex];
} else {
$travelDataFromState = $inputTravel_data['from_state'][$temporaryIndex] ?? '';
}
$travelDataFromCountry = '';
if ($inputTravel_data['from_country'][$temporaryIndex] == '') {
if (($temporaryIndex-1) <= 0) {
$temporaryIndex = 0;
} else {
$temporaryIndex = $temporaryIndex - 1;
}
$travelDataFromCountry = $inputTravel_data['to_country'][$temporaryIndex];
} else {
$travelDataFromCountry = $inputTravel_data['from_country'][$temporaryIndex] ?? '';
}
$travelLeg = new TravelLeg;
$travelLeg->travel_id = $travel->id;
$travelLeg->transport_type_id = $inputTravel_data['transport_type_id'][$i];
$travelLeg->accommodation = $inputTravel_data['accommodation'][$i];
$travelLeg->travel_region_id = $inputTravel_data['travel_region_id'][$i];
$travelLeg->travel_purpose = TravelPurpose::find($inputTravel_data['travel_purpose_id'][$i])->name;
$travelLeg->description = $inputTravel_data['description'][$i];
$travelLeg->travel_prefernces = $inputTravel_data['travel_preferences'][$i];
$travelLeg->add_passengers = $inputTravel_data['add_passengers'][$i];
$travelLeg->from = $inputTravel_data['from'][$i];
$travelLeg->from_state = $travelDataFromState;
$travelLeg->from_country = $travelDataFromCountry;
$travelLeg->to = $inputTravel_data['to'][$i];
$travelLeg->to_state = $inputTravel_data['to_state'][$i] ?? '';
$travelLeg->to_country = $inputTravel_data['to_country'][$i] ?? '';
$travelLeg->departure_date = date('Y-m-d', strtotime(str_replace('/', '-', $inputTravel_data['departure_date'][$i])));
$travelLeg->title = 'Travel Leg ' . $inputs['travelLeg'][$i+1];
$travelLeg->is_official_date = $inputTravel_data['is_official_date'][$i];
$travelLeg->mode_of_transport = TransportType::find($inputTravel_data['transport_type_id'][$i])->name;
$travelLeg->region = TravelRegion::find($inputTravel_data['travel_region_id'][$i])->name;
$travelLeg->travel_purpose_id = $inputTravel_data['travel_purpose_id'][$i];
$travelLeg->processed = 0;
$travelLeg->save();
if ($travelLeg->is_official_date == self::IS_OFFICIALDATE)
{
$travelLeg->official_date()->delete();
}
if ($travelLeg->is_official_date == self::IS_NOT_OFFICIALDATE)
{
$travelLeg->official_date()->delete();
$dates = $inputs['OfficialDate'][$inputs['travelLeg'][$i+1]];
for ($j = 0; $j < count($dates['from']); $j++)
{
$fromODate = new TravelDate;
$fromODate->travel_leg_id = $travelLeg->id;
$fromODate->from = date('Y-m-d', strtotime(str_replace('/', '-', $dates['from'][$j])));
$fromODate->to = date('Y-m-d', strtotime(str_replace('/', '-', $dates['to'][$j])));
$fromODate->save();
}
}
}
}
}
else {
if($user->id != $inputs['user_id']){
$user = User::find($inputs['user_id']);
}
$travel = $user->travels()->create([
'status' => $inputs['status'],
'title' => $travelTitle,
'is_multicity' => $multiCity,
'is_return_trip' => $is_return_trip,
'company_id' => $user->company_id,
'submitted_by_pa' => $inputs['user_id'] != Auth::user()->id ? 0 : 1,
'pa_id' => $inputs['user_id'] != Auth::user()->id ? $inputs['pa_id'] : null,
]);
$this->generateRef($travel);
if($request->has('is_return_trip'))
{
$travelLeg = new TravelLeg;
$travelLeg->travel_id = $travel->id;
$travelLeg->transport_type_id = $inputTravel_data['transport_type_id'];
$travelLeg->accommodation = $inputTravel_data['accommodation'];
$travelLeg->travel_region_id = $inputTravel_data['travel_region_id'];
$travelLeg->travel_purpose = TravelPurpose::find($inputTravel_data['travel_purpose_id'])->name;
$travelLeg->description = $inputTravel_data['description'];
$travelLeg->travel_prefernces = $inputTravel_data['travel_preferences'];
$travelLeg->add_passengers = $inputTravel_data['add_passengers'];
$travelLeg->from = $inputTravel_data['from'];
$travelLeg->from_state = $inputTravel_data['from_state'] ?? '';
$travelLeg->from_country = $inputTravel_data['from_country'] ?? '';
$travelLeg->to = $inputTravel_data['to'];
$travelLeg->to_state = $inputTravel_data['to_state'] ?? '';
$travelLeg->to_country = $inputTravel_data['to_country'] ?? '';
$travelLeg->departure_date = date('Y-m-d', strtotime(str_replace('/', '-', $inputTravel_data['departure_date'])));
if (!empty($inputTravel_data['return_date']))
{
$travelLeg->return_date = date('Y-m-d', strtotime(str_replace('/', '-', $inputTravel_data['return_date'])));
}
$travelLeg->title = 'Travel Leg 1';
$travelLeg->is_official_date = $inputTravel_data['is_official_date'];
$travelLeg->mode_of_transport = TransportType::find($inputTravel_data['transport_type_id'])->name;
$travelLeg->region = TravelRegion::find($inputTravel_data['travel_region_id'])->name;
$travelLeg->travel_purpose_id = $inputTravel_data['travel_purpose_id'];
$travelLeg->processed = 0;
$travelLeg->save();
if ($travelLeg->is_official_date == self::IS_NOT_OFFICIALDATE)
{
for ($i = 0; $i < count($inputs['fromOfficialDate']); $i++)
{
$travelDate = new TravelDate;
$travelDate->travel_leg_id = $travelLeg->id;
$travelDate->from = date('Y-m-d', strtotime(str_replace('/', '-', $inputs['fromOfficialDate'][$i])));
$travelDate->to =date('Y-m-d', strtotime(str_replace('/', '-', $inputs['toOfficialDate'][$i])));
$travelDate->save();
}
}
}
else
{
for ($i = 0; $i < $count; $i++)
{
$travelDataFromState ='';
$temporaryIndex = $i;
if ($inputTravel_data['from_state'][$temporaryIndex] == '') {
if (($temporaryIndex-1) <= 0) {
$temporaryIndex = 0;
} else {
$temporaryIndex = $temporaryIndex - 1;
}
$travelDataFromState = $inputTravel_data['to_state'][$temporaryIndex];
} else {
$travelDataFromState = $inputTravel_data['from_state'][$temporaryIndex] ?? '';
}
$travelDataFromCountry = '';
if ($inputTravel_data['from_country'][$temporaryIndex] == '') {
if (($temporaryIndex-1) <= 0) {
$temporaryIndex = 0;
} else {
$temporaryIndex = $temporaryIndex - 1;
}
$travelDataFromCountry = $inputTravel_data['to_country'][$temporaryIndex];
} else {
$travelDataFromCountry = $inputTravel_data['from_country'][$temporaryIndex] ?? '';
}
$travelLeg = new TravelLeg;
$travelLeg->travel_id = $travel->id;
$travelLeg->transport_type_id = $inputTravel_data['transport_type_id'][$i];
$travelLeg->accommodation = $inputTravel_data['accommodation'][$i];
$travelLeg->travel_region_id = $inputTravel_data['travel_region_id'][$i];
$travelLeg->travel_purpose = TravelPurpose::find($inputTravel_data['travel_purpose_id'][$i])->name;
$travelLeg->description = $inputTravel_data['description'][$i];
$travelLeg->travel_prefernces = $inputTravel_data['travel_preferences'][$i];
$travelLeg->add_passengers = $inputTravel_data['add_passengers'][$i];
$travelLeg->from = $inputTravel_data['from'][$i];
$travelLeg->from_state = $travelDataFromState;
$travelLeg->from_country = $travelDataFromCountry;
$travelLeg->to = $inputTravel_data['to'][$i];
$travelLeg->to_state = $inputTravel_data['to_state'][$i] ?? '';
$travelLeg->to_country = $inputTravel_data['to_country'][$i] ?? '';
$travelLeg->departure_date = date('Y-m-d', strtotime( str_replace('/', '-', $inputTravel_data['departure_date'][$i])));
$travelLeg->title = 'Travel Leg ' . $inputs['travelLeg'][$i+1];
$travelLeg->is_official_date = $inputTravel_data['is_official_date'][$i];
$travelLeg->mode_of_transport = TransportType::find($inputTravel_data['transport_type_id'][$i])->name;
$travelLeg->region = TravelRegion::find($inputTravel_data['travel_region_id'][$i])->name;
$travelLeg->travel_purpose_id = $inputTravel_data['travel_purpose_id'][$i];
$travelLeg->processed = 0;
$travelLeg->save();
if ($travelLeg->is_official_date == self::IS_NOT_OFFICIALDATE)
{
$dates = $inputs['OfficialDate'][$inputs['travelLeg'][$i+1]];
for ($j = 0; $j < count($dates['from']); $j++)
{
$fromODate = new TravelDate;
$fromODate->travel_leg_id = $travelLeg->id;
$fromODate->from = date('Y-m-d', strtotime(str_replace('/', '-', $dates['from'][$j])));
$fromODate->to = date('Y-m-d', strtotime(str_replace('/', '-', $dates['to'][$j])));
$fromODate->save();
}
}
}
}
}
if($inputs['status'] == 'SB')
{
$pivotT = \DB::table('travel_approver_inboxes')
->where('travel_id', $travel->id)
->where('removed',0)
->get();
foreach($pivotT as $p) {
$travel->approver()
->newPivotStatement()
->where('id', $p->id)->update(['removed'=> 1]);
}
(new TravelApprover($travel))->assign();
$travel->update(['submitted_date' => $today,'remark'=> null]);
$travel->fresh();
// (new Notification)->addNotification($travel,'travel');
// dd($travel->approver->last());
}
return redirect(action('Web\TravelController#index'));
}
}
so as you can the main redirect is here:
if(!$inputTravel_data['from_country']){
return redirect()->back();
Sometimes you may wish to redirect the user to their previous location, such as when a submitted form is invalid. You may do so by using the global back helper function. Since this feature utilizes the session, make sure the route calling the back function is using the web middleware group or has all of the session middleware applied:
Route::post('user/profile', function () {
return back()->withInput();
});
I suggest you read through the docs, as it is explained clearly and simple over there: https://laravel.com/docs/5.6/requests#old-input

Laravel 5.5 Crud Routing

I am new to Laravel 5.5 and I am trying to create a CRUD. Right now I am experiencing a views error. I am not sure where I went wrong. If someone point me in the right direction it would be greatly appreciated.
I have tried a few different attempts at resolving this issue such as changing my routes to Uppercase L instead of lower case l for leads to have it follow the directory casing but no avail.
My error
Route [leads.create] not defined. (View: .../resources/views/leads/index.blade.php)
Error's source coming from my index.blade.php file
<div class="pull-right">
<div class="btn-group"> <a href="{{ route('leads.create') }}" class="btn btn-info" >Add New</a> </div>
</div>
My Tree
views
|-- leads
| |-- create.blade.php
| |-- edit.blade.php
| |-- index.blade.php
| `-- show.blade.php
My Web.php
// Leads
Route::resource('Leads','LeadsController');
Route::get('leads/index', function () { return view('Leads.index'); });
Route::get('leads/create', function () { return view('Leads.create'); });
My Controller
namespace App\Http\Controllers;
use App\Leads;
use Illuminate\Http\Request;
class LeadsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$videos = Leads::orderBy('id','DESC')->paginate(5);
return view('leads.index',compact('leads'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('leads.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'first_name' => 'required',
'primary_phone' => 'required',
]);
Leads::create($request->all());
return redirect()->route('leads.index')
->with('success','Lead created successfully');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$leads = Leads::find($id);
return view('leads.show',compact('leads'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$leads = Leads::find($id);
return view('leads.edit',compact('leads'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'first_name' => 'required',
'primary_phone' => 'required',
]);
Leads::find($id)->update($request->all());
return redirect()->route('leads.index')
->with('success','Lead updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
Leads::find($id)->delete();
return redirect()->route('leads.index')
->with('success','Lead deleted successfully');
}
}
You could use url() to go to a url link.
<div class="pull-right">
<div class="btn-group"> <a href="{{ url('leads/create') }}" class="btn btn-info" >Add New</a> </div>
</div>
Or you could use named route
Route::get('leads/create', function () {
return view('Leads.create');
})->name('leads.create');
Create Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Contact;
use Hash;
class ContactController extends Controller
{
public function index(Request $request)
{
$search = $request->get('search');
$field = $request->get('field') != '' ? $request->get('field') : 'first_name';
$sort = $request->get('sort') != '' ? $request->get('sort') : 'asc';
$contacts = new Contact();
$contacts = $contacts->where('first_name', 'like', '%' . $search . '%')
->orderBy($field, $sort)
->paginate(10)
->withPath('?search=' . $search . '&field=' . $field . '&sort=' . $sort);
return view('contacts.index', compact('contacts'))
->with('i', ($request->input('page', 1) - 1) * 10);
}
public function create()
{
return view('contacts.create');
}
public function store(Request $request)
{
$request->validate([
'first_name'=>'required|min:3|max:50',
'last_name'=>'required|min:3|max:50',
'email'=>'required|email|unique:contacts',
'phone' => 'required|numeric|phone',
'password' =>'required|min:3|max:20',
'confirm_password' =>'required|min:3|max:20|same:password'
]);
$contact = new Contact([
'first_name' => $request->get('first_name'),
'last_name' => $request->get('last_name'),
'email' => $request->get('email'),
'job_title' => $request->get('job_title'),
'city' => $request->get('city'),
'country' => $request->get('country'),
'phone' => $request->get('phone'),
'password' => $request->get('password')
]);
$contact->save();
return redirect('/contacts/index')->with('success', 'Contact saved!');
}
public function edit($id)
{
$contact = Contact::find($id);
//print_r($contact);exit;
return view('contacts.edit', compact('contact'));
}
public function update(Request $request, $id)
{
$request->validate([
'first_name'=>'required|min:3|max:50',
'last_name'=>'required|min:3|max:50',
'email'=>'required|email',
'city' => 'required'
]);
$contact = Contact::find($id);
$contact->first_name = $request->get('first_name');
$contact->last_name = $request->get('last_name');
$contact->email = $request->get('email');
$contact->job_title = $request->get('job_title');
$contact->city = $request->get('city');
$contact->country = $request->get('country');
$contact->phone = $request->get('phone');
$contact->password = $request->get('password');
$contact->save();
return redirect('/contacts/index')->with('success', 'Contact updated!');
}
public function delete($id)
{
$contact = Contact::find($id);
$contact->delete();
return redirect('/contacts/index')->with('success', 'Contact deleted!');
}
}
Create Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
protected $fillable = [
'first_name',
'last_name',
'email',
'city',
'country',
'job_title',
'phone',
'password'
];
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
}
Create routes in web.php
Route::get('contacts/index', 'ContactController#index');
Route::get('contacts/create', 'ContactController#create');
Route::post('contacts/store', 'ContactController#store');
Route::get('contacts/edit/{id}', 'ContactController#edit');
Route::post('contacts/update/{id}', 'ContactController#update');
Route::post('contacts/delete/{id}','ContactController#delete');
Route::post('contacts/index', 'ContactController#index');
create base.blade.php in resources/views folder
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laravel 5.8 & MySQL CRUD Tutorial</title>
<link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
#yield('main')
</div>
<script src="{{ asset('js/app.js') }}" type="text/js"></script>
</body>
</html>
Create index.blade.php in contacts folder
#extends('base')
#section('main')
<div class="col-sm-12">
#if(session()->get('success'))
<div class="alert alert-success">
{{ session()->get('success') }}
</div>
#endif
</div>
<div class="row">
<div class="col-sm-12">
<h1 class="display-3">Contacts</h1>
<a class="pull-right btn btn-primary" href="<?php echo url('contacts/create') ?>">Add Contacts</a>
</div>
</div>
<div class="row">
<form action="<?php echo url('contacts/index')?>" method="post">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<button class="pull-right btn btn-primary" href="<?php echo url('contacts/index') ?>">view all</button>
<div class="pull-right col-lg-3 input-group custom-search-form">
<input class="form-control" name="search" placeholder="Search..." type="text" value="{{ request('search') }}">
<span class="input-group-btn ">
<button class="btn btn-default" type="submit">
<i class="fa fa-search"></i>
</button>
</span>
</div>
<input type="hidden" value="{{request('field')}}" name="field"/>
<input type="hidden" value="{{request('sort')}}" name="sort"/>
<table class="table table-striped">
<thead>
<tr>
<td>ID</td>
<td>
<a href="{{url('contacts/index')}}?search={{request('search')}}&field=first_name&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
Name
</a>
{{request('field','first_name')=='first_name'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</td>
<td>
<a href="{{url('contacts/index')}}?search={{request('search')}}&field=email&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
Email
</a>
{{request('field','email')=='email'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</td>
<td>
<a href="{{url('contacts/index')}}?search={{request('search')}}&field=job_title&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
Job Title
</a>
{{request('field','job_title')=='job_title'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</td>
<td>
<a href="{{url('contacts/index')}}?search={{request('search')}}&field=city&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
City
</a>
{{request('field','city')=='city'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</td>
<td>
<a href="{{url('contacts/index')}}?search={{request('search')}}&field=country&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
Country
</a>
{{request('field','country')=='country'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</td>
<td colspan = 2>Actions</td>
</tr>
</thead>
<tbody>
#foreach($contacts as $contact)
<tr>
<td>{{$contact->id}}</td>
<td>{{$contact->first_name}} {{$contact->last_name}}</td>
<td>{{$contact->email}}</td>
<td>{{$contact->job_title}}</td>
<td>{{$contact->city}}</td>
<td>{{$contact->country}}</td>
<td>
Edit
</td>
<td>
<form action="delete/<?php echo $contact->id?>" method="post">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<button class="btn btn-danger" type="submit">Delete</button>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
</form>
</div>
#endsection
Create form create.blade.php
#extends('base')
#section('main')
<div class="row">
<div class="col-sm-8 offset-sm-2">
<h1 class="display-3">Add a contact</h1>
<div>
<form method="post" action="{{ url('contacts/store') }}">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="first_name">First Name:</label>
<input type="text" class="form-control" name="first_name"/>
<span class="text-danger">{{ $errors->first('first_name') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="last_name">Last Name:</label>
<input type="text" class="form-control" name="last_name"/>
<span class="text-danger">{{ $errors->first('last_name') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" name="email"/>
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="phone">Phone:</label>
<input type="text" class="form-control" name="phone"/>
<span class="text-danger">{{ $errors->first('phone') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="city">City:</label>
<input type="text" class="form-control" name="city"/>
<span class="text-danger">{{ $errors->first('city') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="country">Country:</label>
<input type="text" class="form-control" name="country"/>
<span class="text-danger">{{ $errors->first('country') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" name="password"/>
<span class="text-danger">{{ $errors->first('password') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="confirm_password">Confrim Password:</label>
<input type="password" class="form-control" name="confirm_password"/>
<span class="text-danger">{{ $errors->first('confirm_password') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="job_title">Job Title:</label>
<input type="text" class="form-control" name="job_title"/>
<span class="text-danger">{{ $errors->first('job_title') }}</span>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Add contact</button>
</form>
</div>
</div>
</div>
#endsection
Create edit.blade.php
#extends('base')
#section('main')
<div class="row">
<div class="col-sm-8 offset-sm-2">
<h1 class="display-3">Update a contact</h1>
<form method="post" action="{{ url('contacts/update', $contact->id) }}">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="first_name">First Name:</label>
<input type="text" class="form-control" name="first_name" value="<?php echo $contact->first_name ?>" />
<span class="text-danger">{{ $errors->first('first_name') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="last_name">Last Name:</label>
<input type="text" class="form-control" name="last_name" value="<?php echo $contact->last_name ?>" />
<span class="text-danger">{{ $errors->first('last_name') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" name="email" value="<?php echo $contact->email ?>" />
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="phone">Phone:</label>
<input type="text" class="form-control" name="phone" value="<?php echo $contact->phone ?>" />
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="city">City:</label>
<input type="text" class="form-control" name="city" value="<?php echo $contact->city ?>" />
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="country">Country:</label>
<input type="text" class="form-control" name="country" value="<?php echo $contact->country ?>" />
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="job_title">Job Title:</label>
<input type="text" class="form-control" name="job_title" value='<?php echo $contact->job_title;?>' />
</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Update</button>
</form>
</div>
</div>
#endsection
Phone number validation put this code in AppServiceProvider.php in boot function
Validator::extend('phone', function($attribute, $value, $parameters, $validator) {
return substr($value, 0, 3) == '+91';
});
Link for Crud Operation - https://www.techiediaries.com/php-laravel-crud-mysql-tutorial/

How to use CRUD operation in Laravel 5.4

I am new to Laravel. I want to use MongoDB with laravel so I have installed mongodb and configured php extension also(copied mongo dll file) and it works fine.
Now I want to use CRUD operation in laravel using mongoDB. How can I use. How to create model. What I need to modify in model.
Note: show me model code. In model what I have to write.
Thank You
It seems that there's a package that enables you to use MongoDB with Eloquent. I'm not a fan of linking external sources without quoting information here, but copying their readme sounds counterproductive as well. The instructions seem easy enough, so I hope this can help you: Laravel MongoDB.
Example code MongoDb + Php:
Insert:
$mongo = new MongoClient();
$db = $mongo->mydb1;
$data = array('emp_id' => '1', 'first_name' => 'Tiger' , 'last_name' => 'Nixon', 'position' => 'System Architect', 'email' => 't.nixon#datatables.net', 'office' => 'Edinburgh', 'start_date' => '2011-04-25 00:00:00', 'age' => '61', 'salary' => '320800', 'projects' => array('Project1', 'Project2', 'Project3'));
$collection = $db->createCollection("emp_details");
if($collection->insert($data))
{
echo '<p style="color:green;">Record inserted successfully</p>';
}
Update:
$mongo = new MongoClient();
$db = $mongo->mydb1;
/* Note: Here we are using the update() method. The update() method update values in the existing document */
$collection = $db->createCollection("emp_details");
$newdata = array('$set' => array("age" => "55", "salary" => "320000"));
// specify the column name whose value is to be updated. If no such column than a new column is created with the same name.
$condition = array("emp_id" => "1");
// specify the condition with column name. If no such column exist than no record will update
if($collection->update($condition, $newdata))
{
echo '<p style="color:green;">Record updated successfully</p>';
}
else
{
echo '<p style="color:red;">Error in update</p>';
}
Delete:
$mongo = new MongoClient();
// name of database which is to be created
$db_name = 'local';
// get the list of database and check if DB exist, if not than create it.
$dblists = $mongo->listDBs();
if(count($dblists) > 0)
{
$count = 0;
$exist = false;
foreach($dblists['databases'] as $databases)
{
if($databases['name'] == $db_name)
{
$exist = true;
break;
}
}
}
if($exist)
{
$db = $mongo->db_name; // select the db which is to be deleted
if($db)
{
if($db->drop())
{
echo '<p style="color:green;">Database deleted successfully</p>';
}
}
}
else
{
echo '<p style="color:red;">No such database exist</p>';
}
In case of Laravel, you have to study the basic CRUD operation then you will use this very well.
Create Customer Controller
<?php
namespace App\Http\Controllers;
use App\Customer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Hash;
class CustomerController extends Controller
{
public function index(Request $request)
{
$search = $request->get('search');
$field = $request->get('field') != '' ? $request->get('field') : 'firstname';
$sort = $request->get('sort') != '' ? $request->get('sort') : 'asc';
$customers = new Customer();
$customers = $customers->where('firstname', 'like', '%' . $search . '%')
->orderBy($field, $sort)
->paginate(5)
->withPath('?search=' . $search . '&field=' . $field . '&sort=' . $sort);
return view('theme.customers_list', compact('customers'))
->with('i', ($request->input('page', 1) - 1) * 5);
}
public function add()
{
return view('theme.customer_form');
}
public function add_record(Request $request)
{
$this->validate($request,
[
'firstname' =>'required|max:20',
'lastname' =>'required|max:20',
'email' =>'required|email|unique:users',
'password' =>'required|min:3|max:20',
'confirm_password' =>'required|min:3|max:20|same:password',
'phone' =>'required|numeric|phone',
'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048'
], [
'firstname.required' => ' The first name field is required.',
//'firstname.min' => ' The first name must be at least 5 characters.',
'firstname.max' => ' The first name may not be greater than 20 characters.',
'lastname.required' => ' The last name field is required.',
//'lastname.min' => ' The last name must be at least 5 characters.',
'lastname.max' => ' The last name may not be greater than 20 characters.',
]);
$customers = new Customer;
$customers->firstname = $request->input('firstname');
$customers->lastname = $request->input('lastname');
$customers->email = $request->input('email');
$customers->phone = $request->input('phone');
$customers->password = Hash::make($request->input('password'));
$customers->confirm_password = $request->input('confirm_password');
if($request->hasFile('image'))
{
$filename = $request->image->getClientOriginalName();
$request->image->storeAs('public/uploads',$filename);
}
$customers->image = $filename;
$customers->save();
return redirect()->action('CustomerController#index');
}
public function edit($id)
{
$customers = Customer::find($id);
return view('theme.customer_edit',compact('customers'));
}
public function update(Request $request, $id)
{
$this->validate($request,
[
'firstname' =>'required|max:20',
'lastname' =>'required|max:20',
'email' =>'required|email|unique:users',
'password' =>'required|min:3|max:20',
'confirm_password' =>'required|min:3|max:20|same:password',
'phone' =>'required|numeric|phone',
'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048'
], [
'firstname.required' => ' The first name field is required.',
//'firstname.min' => ' The first name must be at least 5 characters.',
'firstname.max' => ' The first name may not be greater than 20 characters.',
'lastname.required' => ' The last name field is required.',
//'lastname.min' => ' The last name must be at least 5 characters.',
'lastname.max' => ' The last name may not be greater than 20 characters.',
]);
$customers = Customer::find($id);
$customers->firstname = $request->input('firstname');
$customers->lastname = $request->input('lastname');
$customers->email = $request->input('email');
$customers->phone = $request->input('phone');
$customers->password = $request->input('password');
$customers->confirm_password = $request->input('confirm_password');
if($request->hasFile('image'))
{
$filename = $request->image->getClientOriginalName();
$request->image->storeAs('public/uploads',$filename);
}
$customers->image = $filename;
$customers->save();
return redirect()->action('CustomerController#index');
}
public function delete($id)
{
Customer::find($id)->delete();
return redirect()->action('CustomerController#index');
}
public function search()
{
$name = Input::get('search');
if ($name != "")
{
$customers = Customer::where('firstname','Like','%' . $name . '%')
->orWhere('email','Like','%' . $name . '%')
->get();
return view('theme.customers_list',compact('customers'));
}
else
{
dd('no data found');
}
}
public function login()
{
return view('theme.login');
}
public function do_login(Request $request)
{
$email=$request->input('email');
$password = Hash::check($request->input('password'));
dd($password);exit();
$data=with(new Customer)->SignIn($email,$password);
$row=count($data);
if($row > 0){
echo "Login success";
}else{
echo "usename and password Mismatch!";
}
}
}
Now create customer_form.blade.php
#extends('theme.default')
#section('content')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<div id="">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Add Customer</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div class="panel-body">
<!-- #if (count($errors) > 0)
<div class = "alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif -->
<form role="form" action="<?php echo url('customer/add_record')?>" id="add_customer" method="post" enctype="multipart/form-data">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('firstname') ? 'has-error' : '' }}">
<label for="firstname">Firstname</label>
<input type="text" name="firstname" id="firstname" class="form-control" placeholder="Firstname">
<span class="text-danger">{{ $errors->first('firstname') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group {{ $errors->has('lastname') ? 'has-error' : '' }}">
<label for="lastname">Lastname</label>
<input type="text" name="lastname" id="lastname" class="form-control" placeholder="Lastname">
<span class="text-danger">{{ $errors->first('lastname') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('email') ? 'has-error' : '' }}">
<label for="email">Email</label>
<input type="text" name="email" id="email" class="form-control" placeholder="Email">
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group {{ $errors->has('phone') ? 'has-error' : '' }}">
<label for="phone">Contact Number</label>
<input type="text" name="phone" id="phone" class="form-control" placeholder="Contact Number">
<span class="text-danger">{{ $errors->first('phone') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('password') ? 'has-error' : '' }}">
<label for="password">Password</label>
<input type="password" name="password" id="password" class="form-control" placeholder="Password">
<span class="text-danger">{{ $errors->first('password') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group {{ $errors->has('confirm_password') ? 'has-error' : '' }}">
<label for="confirm_password">Confirm Password</label>
<input type="password" name="confirm_password" id="confirm_password" class="form-control" placeholder="Confirm Password">
<span class="text-danger">{{ $errors->first('confirm_password') }}</span>
</div>
</div>
</div>
<div class="row">
<div class= "col-lg-6">
<div class="form-group">
<label>Image</label>
<input type="file" name="image" id="image">
</div>
</div>
<!-- <div class= "col-lg-6">
<div class="form-group">
<label>Text area</label>
<textarea class="form-control" rows="3"></textarea>
</div>
</div> -->
</div>
<button type="submit" valur="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Cancel</button>
</form>
<!-- /.col-lg-6 (nested) -->
<!-- /.col-lg-6 (nested) -->
<!-- /.row (nested) -->
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#add_customer').validate({
rule: {
firstname: {
required: true,
}
},
messages: {
firstname: {
required:"firstname name cannot be blank."
}
},
});
});
</script>
#endsection
create list view customer_list.blade.php
#extends('theme.default')
#section('content')
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Users
<a class="pull-right btn btn-primary" href="<?php echo url('customer/add') ?>">Add Customer</a></h1>
</div>
<!-- /.col-lg-12 -->
</div>
<form action="<?php echo url('customer/index')?>" method="post">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<button class="pull-right btn btn-primary" href="<?php echo url('customer/index') ?>">view all</button>
<div class="pull-right col-lg-3 input-group custom-search-form">
<input class="form-control" name="search" placeholder="Search..." type="text" value="{{ request('search') }}">
<span class="input-group-btn ">
<button class="btn btn-default" type="submit">
<i class="fa fa-search"></i>
</button>
</span>
</div>
<input type="hidden" value="{{request('field')}}" name="field"/>
<input type="hidden" value="{{request('sort')}}" name="sort"/>
<!-- <button type="button" class="pull-right btn btn-primary">Add Customer</button> -->
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>#</th>
<th>Iamge</th>
<th>
<a href="{{url('customer/index')}}?search={{request('search')}}&field=firstname&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
FirstName
</a>
{{request('field','firstname')=='firstname'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</th>
<th>
<a href="{{url('customer/index')}}?search={{request('search')}}&field=lastname&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
LastName
</a>
{{request('field','lastname')=='lastname'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</th>
<th>
<a href="{{url('customer/index')}}?search={{request('search')}}&field=email&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
Email
</a>
{{request('field','email')=='email'?(request('sort','asc')=='asc'?'▴':'▾'):''}}</th>
</th>
<th>
<a href="{{url('customer/index')}}?search={{request('search')}}&field=phone&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
Phone Number
</a>
{{request('field','phone')=='phone'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</th>
<th colspan="2">Action</th>
</tr>
</thead>
<tbody>
#php
$i=1;
#endphp
<?php foreach ($customers as $customer)
{
?>
<tr>
<td><?php echo $i++;?></td>
<td> <img height="50px" width="50px" class="user-pic" src="<?php echo asset("/storage/uploads/$customer->image")?>"></td>
<td><?php echo $customer->firstname;?></td>
<td><?php echo $customer->lastname;?></td>
<td><?php echo $customer->email;?></td>
<td><?php echo $customer->phone;?></td>
<td><a href ='edit/<?php echo $customer->id?>'>Edit</a></td>
<td><a href ='delete/<?php echo $customer->id?>'>Delete</a></td>
</tr>
<?php
}
?>
</tbody>
</table>
<nav>
<ul class="pagination justify-content-end pull-right">
{{$customers->links('vendor.pagination.bootstrap-4')}}
</ul>
</nav>
</form>
#endsection
create edit form customer_edit.blade.php
#extends('theme.default')
#section('content')
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script> -->
<div id="">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Add Customer</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div class="panel-body">
<!-- #if (count($errors) > 0)
<div class = "alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif -->
<form role="form" action="{{ url('customer/update', $customers->id)}}" id="add_customer" method="post" enctype="multipart/form-data">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('firstname') ? 'has-error' : '' }}">
<label for="firstname">Firstname</label>
<input type="text" name="firstname" id="firstname" value="<?php echo $customers->firstname;?>" class="form-control" placeholder="Firstname">
<span class="text-danger">{{ $errors->first('firstname') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group {{ $errors->has('lastname') ? 'has-error' : '' }}">
<label for="lastname">Lastname</label>
<input type="text" name="lastname" id="lastname" value="<?php echo $customers->lastname;?>" class="form-control" placeholder="Lastname">
<span class="text-danger">{{ $errors->first('lastname') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('email') ? 'has-error' : '' }}">
<label for="email">Email</label>
<input type="text" name="email" id="email" value="<?php echo $customers->email;?>" class="form-control" placeholder="Email">
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group {{ $errors->has('phone') ? 'has-error' : '' }}">
<label for="phone">Contact Number</label>
<input type="text" name="phone" id="phone" value="<?php echo $customers->phone;?>" class="form-control" placeholder="Contact Number">
<span class="text-danger">{{ $errors->first('phone') }}</span>
</div>
</div>
</div>
<div class="row">
<div class= "col-lg-6">
<div class="form-group">
<label>Image</label>
<div class="fileinput-preview thumbnail" id="profile" data-trigger="fileinput" style="width: 60px; height: 60px;">
<img height="90px" width="70px" class="user-pic" src="<?php echo asset("/storage/uploads/$customers->image")?>">
</div>
<input type="file" name="image" id="image">
</div>
</div>
<!-- <div class= "col-lg-6">
<div class="form-group">
<label>Text area</label>
<textarea class="form-control" rows="3"></textarea>
</div>
</div> -->
</div>
<button type="submit" valur="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Cancel</button>
</form>
<!-- /.col-lg-6 (nested) -->
<!-- /.col-lg-6 (nested) -->
<!-- /.row (nested) -->
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
</div>
#endsection
create Model Customer.php
<?php
namespace App;
use DB;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
public function SignIn($email,$password)
{
$sql=DB::table('customers')->where('email',$email)->where('password',$password)->get();
return $sql;
}
}
create routing in web.php
Route::get('home/my-home', 'HomeController#myHome');
Route::get('customer/index', 'CustomerController#index');
Route::get('customer/add', 'CustomerController#add');
Route::post('customer/add_record', 'CustomerController#add_record');
Route::get('customer/edit/{id}', 'CustomerController#edit');
Route::post('customer/update/{id}', 'CustomerController#update');
Route::get('customer/delete/{id}','CustomerController#delete');
Route::post('customer/index','CustomerController#index');
Route::get('customer/login','CustomerController#login');
Route::post('customer/do_login','CustomerController#do_login');
for validation create function in AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Validator;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Validator::extend('phone', function($attribute, $value, $parameters, $validator) {
return substr($value, 0, 3) == '+91';
});
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
}
Create Routes
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/role', 'RoleController#index')->name('role');
Route::get('/create', 'RoleController#create')->name('role.create');
Route::post('/store', 'RoleController#store')->name('role.store');
Route::get('/edit/{id}', 'RoleController#edit')->name('role.edit');
Route::post('/update/{id}', 'RoleController#update')->name('role.update');
Route::any('/destroy/{id}', 'RoleController#destroy')->name('role.destroy');
Create Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Role;
use Validate;
use Collective\Html\FormFacade;
class RoleController extends Controller
{
public function index(){
$roles = Role::all();
return view('role.index',compact('roles'));
}
public function create(){
return view('role.create');
}
public function store(Request $request)
{
request()->validate([
'name' => 'required',
]);
Role::create($request->all());
return redirect()->route('role')
->with('success','Role created successfully');
}
public function edit($id){
$roles = Role::find($id);
return view('role.edit',compact('roles'));
}
public function update(Request $request, $id){
request()->validate([
'name' => 'required',
]);
Role::find($id)->update($request->all());
return redirect()->route('role')
->with('success','Role updated successfully');
}
public function destroy($id)
{
Role::find($id)->delete($id);
return redirect()->route('role')
->with('success','Role updated successfully');
}
}
Create Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
protected $fillable = [ 'name' ];
}
create layoyt file in layouts folder
<!DOCTYPE html>
<html>
<head>
<title>Laravel 5.5 CRUD Application</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="container">
#yield('content')
</div>
</body>
</html>
create index.blade.php
#extends('layouts.layout')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Role</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('role.create') }}"> Create New role</a>
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered">
<tr>
<th>No</th>
<th>Name</th>
<th width="280">Action</th>
</tr>
#foreach ($roles as $role)
<tr>
<td>{{ $role->id }}</td>
<td>{{ $role->name}}</td>
<td>
<a class="btn btn-primary" href="{{ route('role.edit',$role->id) }}">Edit</a>
<form action="{{ route('role.destroy', $role->id) }}" method="DELETE">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<button class="btn btn-danger" type="submit">Delete</button>
</form>
<!-- <button class="deleteRecord" data-id="{{ $role->id }}" >Delete Record</button> -->
</td>
</tr>
#endforeach
</table>
#endsection
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$(".deleteRecord").click(function(){
var id = $(this).data("id");
//var token = $("meta[name='csrf-token']").attr("content");
$.ajax(
{
url: "destroy/"+id,
type: 'Post',
data: { "id": id, "_token": "{{ csrf_token() }}",},
dataType: "JSON",
success: function (){
console.log("it Works");
}
});
});
});
</script>
Create create.blade.php
#extends('layouts.layout')
#section('content')
<div id="">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Add Role</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div class="panel-body">
<form role="form" action="{{ route('role.store') }}" id="add_customer" method="post" enctype="multipart/form-data">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
<label for="name">Name</label>
<input type="text" name="name" id="name" class="form-control" placeholder="Name">
<span class="text-danger">{{ $errors->first('name') }}</span>
</div>
</div>
</div>
<button type="submit" valur="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Cancel</button>
</form>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
</div>
#endsection
Create edit.blade.php
#extends('layouts.layout')
#section('content')
<div id="">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Add Role</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div class="panel-body">
<form role="form" action="{{ route('role.update',$roles->id) }}" id="update_role" method="post" enctype="multipart/form-data">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
<label for="name">Name</label>
<input type="text" name="name" id="name" class="form-control" value="<?php echo $roles->name ?>" placeholder="Name">
<span class="text-danger">{{ $errors->first('name') }}</span>
</div>
</div>
</div>
<button type="submit" valur="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Cancel</button>
</form>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
</div>
#endsection

Image are not showing and cant update my image in laravel

I am doing a project. In this project I want to update name, websit and image field. I want that if a user choose new one then the field upadted otherwise it retains the past value. this works perfectly okay for my name and website_link. But I cant do the image field looking like this. Please help me guys.
My Controller is
public function edit($id)
{
if (Auth::check()) {
if (Auth::user()->user_role->role_id == 1) {
$sponsor = Sponsor::where('id', $id)->first();
if (!empty($sponsor)) {
$data = array(
'menu' => 'sponsor',
'sub_menu' => 'all',
'sponsor' => $sponsor
);
return view('backends.sponsors.edit', $data);
} else {
Session::flash('error', 'Try again.');
return redirect();
}
} else {
return redirect('');
}
} else {
return redirect('');
}
}
public function update(Request $request, $id)
{
if (Auth::check()) {
if (Auth::user()->user_role->role_id == 1) {
$sponsor = Sponsor::where('id', $id)->first();
if (!empty($sponsor)) {
$rules = array(
'name' => '',
'website_link' => '',
'logo' => ''
);
$valid = Validator::make($request->input(), $rules);
if ($valid->fails()) {
return redirect('sponsors/edit/' . $sponsor->id)->withErrors($valid)->withInput();
} else {
$sponsor->name = $request->input('name');
$sponsor->website_link = $request->input('website_link');
// $sponsor->logo = $request->input('logo');
$photo = $request->file('logo');
if($photo)
{
$ext = $photo->getClientOriginalExtension();
$fileName = rand(100, 5000000) . '.' .$ext;
$sponsor->logo = 'public/assets/uploads/sponsors/'.$fileName;
$photo->move(base_path().'/public/assets/uploads/sponsors/',$fileName);
} else {
}
if ($sponsor->save()) {
Session::flash('success', 'Area of experience updated successful.');
return redirect('sponsors/all');
} else {
Session::flash('error', 'Try again.');
return redirect('sponsors/edit//' . $sponsor->id);
}
}
} else {
Session::flash('error', 'Try again.');
return redirect('sponsors/all');
}
} else {
return redirect('');
}
} else {
return redirect('');
}
}
My view page is
#extends ('backends.layouts.app')
#section('main')
<main id="main-container">
<div class="content bg-gray-lighter">
<div class="row items-push">
<div class="col-sm-7">
<h1 class="page-heading">
Sponsors <small>That feeling of delight when you start your awesome new project!</small>
</h1>
</div>
<div class="col-sm-5 text-right hidden-xs">
<ol class="breadcrumb push-10-t">
<li><a class="link-effect" href="{{ URL::to('admin/dashboard') }}">Home</a></li>
<li>Sponsor</li>
</ol>
</div>
</div>
</div>
<div class="content">
<div class="block">
<div class="block-header">
<h3 class="block-title">Sponsor</h3>
</div>
<div class="col-md-12">
#if(Session::has('success'))
<div class="alert alert-success">
<strong> {{ Session::get('success') }}</strong>
</div>
#endif
#if(Session::has('error'))
<div class="alert alert-danger">
<strong> {{ Session::get('error') }}</strong>
</div>
#endif
</div>
<div class="clearfix"></div>
<div class="block-content">
<form method="POST" action="{{ (!empty($sponsor->id)) ? URL::to('sponsors/edit/'.$sponsor->id) : '' }}" class="push-10-t" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<div class="form-material floating">
<input type="text" name="name" value="{{ (!empty($sponsor->name)) ? $sponsor->name : old('name') }}" id="name" class="form-control" required >
<label for="name">Company Name</label>
</div>
</div>
<div class="form-group">
<div class="form-material floating">
<input type="text" name="website_link" value="{{ (!empty($sponsor->website_link)) ? $sponsor->website_link : old('name') }}" id="website_link" class="form-control" >
<label for="website_link">Website Link</label>
</div>
</div>
<div class="form-group">
<label for="logo">Logo</label><br/>
<div id="prev" style="display: none" class="col-md-3 thumbnail">
<img id="blah" class="img-responsive">
</div>
<div class="clearfix"></div>
<div class="form-group">
<label for="logo"> <span class="btn btn-primary" value="{{ (!empty($sponsor->logo)) ? $sponsor->logo : old('logo') }}" id="fileName0">Browse</span></label>
<input type="file" name="logo" style="visibility: hidden; position: absolute;" value="{{ (!empty($sponsor->logo)) ? $sponsor->logo : old('logo') }}" id="logo" class="form-control" required>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
</div>
</div>
</div>
</main>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#logo").change(function(){
$('#prev').show();
readURL(this);
});
</script>
#endsection
Please help me solving this
The answer will be
public function update(Request $request, $id)
{
if (Auth::check()) {
if (Auth::user()->user_role->role_id == 1) {
$sponsor = Sponsor::where('id', $id)->first();
if (!empty($sponsor)) {
$rules = array(
'name' => 'required',
'website_link' => 'required',
'logo' => ''
);
$valid = Validator::make($request->input(), $rules);
if ($valid->fails()) {
return redirect('sponsors/edit/' . $sponsor->id)->withErrors($valid)->withInput();
} else {
$sponsor->name = $request->input('name');
$sponsor->website_link = $request->input('website_link');
$hdLogo = $request->input('hdLogo');
$photo = $request->file('logo');
if(!empty($photo) && !empty($hdLogo)){
$ext = $photo->getClientOriginalExtension();
$fileName = rand(100, 5000000) . '.' .$ext;
$sponsor->logo = 'public/assets/uploads/sponsors/'.$fileName;
$photo->move(base_path().'/public/assets/uploads/sponsors/',$fileName);
}else if(!empty($photo) && empty($hdLogo)){
$ext = $photo->getClientOriginalExtension();
$fileName = rand(100, 5000000) . '.' .$ext;
$sponsor->logo = 'public/assets/uploads/sponsors/'.$fileName;
$photo->move(base_path().'/public/assets/uploads/sponsors/',$fileName);
}else if(empty($photo) && !empty($hdLogo)){
$sponsor->logo = $sponsor->logo;
}
else if(empty($photo) && empty($hdLogo)){
Session::flash('error','Logo is required.');
return redirect()->back();
}
if ($sponsor->save()) {
Session::flash('success', 'Sponsor updated successful.');
return redirect('sponsors/all');
} else {
Session::flash('error', 'Try again.');
return redirect()->back();
}
}
} else {
Session::flash('error', 'Try again.');
return redirect('sponsors/all');
}
} else {
return redirect('');
}
} else {
return redirect('');
}
}
And the view file will be
#extends ('backends.layouts.app')
#section('main')
<main id="main-container">
<div class="content bg-gray-lighter">
<div class="row items-push">
<div class="col-sm-7">
<h1 class="page-heading">
Sponsors <small>That feeling of delight when you start your awesome new project!</small>
</h1>
</div>
<div class="col-sm-5 text-right hidden-xs">
<ol class="breadcrumb push-10-t">
<li><a class="link-effect" href="{{ URL::to('admin/dashboard') }}">Home</a></li>
<li>Sponsor</li>
</ol>
</div>
</div>
</div>
<div class="content">
<div class="block">
<div class="block-header">
<h3 class="block-title">Sponsor</h3>
</div>
<div class="col-md-12">
#if(Session::has('success'))
<div class="alert alert-success">
<strong> {{ Session::get('success') }}</strong>
</div>
#endif
#if(Session::has('error'))
<div class="alert alert-danger">
<strong> {{ Session::get('error') }}</strong>
</div>
#endif
</div>
<div class="clearfix"></div>
<div class="block-content">
<form method="POST" action="{{ (!empty($sponsor->id)) ? URL::to('sponsors/edit/'.$sponsor->id) : '' }}" class="push-10-t" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<div class="form-material floating">
<input type="text" name="name" value="{{ (!empty($sponsor->name)) ? $sponsor->name : old('name') }}" id="name" class="form-control" required >
<label for="name">Company Name</label>
</div>
</div>
<div class="form-group">
<div class="form-material floating">
<input type="text" name="website_link" value="{{ (!empty($sponsor->website_link)) ? $sponsor->website_link : old('name') }}" id="website_link" class="form-control" >
<label for="website_link">Website Link</label>
</div>
</div>
<div class="form-group">
<label for="logo">Logo</label><br/>
<input type="hidden" value="{{ (!empty($sponsor->logo)) ? $sponsor->logo : ''}}" name="hdLogo">
#if(!empty($sponsor->logo))
<div id="prev" class="col-md-3 thumbnail">
<img id="blah" src="{{ url($sponsor->logo)}}" class="img-responsive">
</div>
#else
<div id="prev" style="display: none" class="col-md-3 thumbnail">
<img id="blah" src="{{ (!empty($sponsor->logo)) ? $sponsor->logo : '' }}" class="img-responsive">
</div>
#endif
<div class="clearfix"></div>
<div class="form-group">
#if(!empty($sponsor->logo))
<label for="logo"> <span class="btn btn-primary" value="{{ (!empty($sponsor->logo)) ? $sponsor->logo : old('logo') }}" id="fileName0">Browse</span></label>
<input type="file" name="logo" style="visibility: hidden; position: absolute;" id="logo" class="form-control">
#else
<label for="logo"> <span class="btn btn-primary" value="{{ (!empty($sponsor->logo)) ? $sponsor->logo : old('logo') }}" id="fileName0">Browse</span></label>
<input type="file" name="logo" style="visibility: hidden; position: absolute;" id="logo" class="form-control" required>
#endif
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
</div>
</div>
</div>
</main>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#logo").change(function(){
$('#prev').show();
readURL(this);
});
</script>
#endsection

Categories