How to stop looping same data in foreach - laravel

So, I make categories for jawaban and if jawaban == 1 then jawaban input type should be a button radio and if jawaban == 2 the input type should be multiple choice but when i am looping the condition jawaban would be looping for all pertanyaans, I just want to loop only for that kegiatan
in blade.php
#foreach ($pertanyaans as $pertanyaan)
#if ($pertanyaan->kategori1 == '1')
<div class="form-group">
<input type="file" name="jawaban" id="jawaban" accept=".png, .jpeg, .jpg" data-allowed-file-extensions='["png", "jpeg", "jpg"]' id="input-file-now" class="dropify" data-max-file-size="3000K" />
<p class="help-block" style="font-size: 12px;">Max Filesize 3 MB (png, jpeg, jpg)</p>
</div>
#endif
#break($pertanyaan->kategori1 == 1)
#if ($pertanyaan->kategori1 == '2')
<div class="form-group">
<textarea class="form-control" id="jawaban" rows="3"></textarea>
</div>
#endif
#break($pertanyaan->kategori1 == 2)
#if ($pertanyaan->kategori1 == '3')
<div class="form-group" id="jawaban">
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="pilihan" id="pilihan1" value="option1">
<label class="form-check-label" for="inlineRadio1">Sangat Tidak Sesuai</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="pilihan" id="pilihan2" value="option2">
<label class="form-check-label" for="inlineRadio2">Tidak Sesuai</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="pilihan" id="pilihan3" value="option1">
<label class="form-check-label" for="inlineRadio1">Lumayan Sesuai</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="pilihan" id="pilihan4" value="option2">
<label class="form-check-label" for="inlineRadio2">Sesuai</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="pilihan" id="pilihan5" value="option2">
<label class="form-check-label" for="inlineRadio2">Sangat Sesuai</label>
</div>
</div>
#endif
in my controller :
$list_pelaporan = PelaporanEfektivitas::all();
$kategori = kategori_pertanyaan::all();
$kegiatan = kegiatan::all();
$pertanyaans = PertanyaanEfektivitas::all();
if ($request->ajax()) {
return datatables()->of($list_pelaporan)
->addColumn('action', function ($data) {
$button = '<i class="fa fa-plus"></i> Pelaporan';
$button .= ' ';
$button .= '<button type="button" name="detail" data-toggle="tooltip" name="detail" data-id="'.$data->id.'" class="detail btn btn-info detail-modal"><i class="fa fa-eye"></i> Detail</button>';
$button .= ' ';
$button .= '<button type="button" name="delete" id="'.$data->id.'" class="delete btn btn-danger"><i class="far fa-trash-alt"></i> Delete</button>';
return $button;
})
->rawColumns(['action'])
->addIndexColumn()
->make(true);
};
return view('pelaporan.efektivitas', compact('kategori','kegiatan','list_pelaporan', 'pertanyaans'));

You may want to use Switch Statements for multiple conditions
#switch($pertanyaan->kategori1)
#case(1)
// First case...
#break
#case(2)
// Second case...
#break
#case(3)
// Third case...
#break
#default
// Default case...
#endswitch

Related

Laravel : Next Record in a random Order

im creating a quiz app for driving lessons. the quiz page have all the data but i want to do next button to take you to the next question but in in a random order.
this is my controller's function for the next but it's not working But it worked with me in another project
public function submitans(Request $request) {
$nextq = Session::get('nextq');
$wrongans = Session::get('wrongans');
$correctans = Session::get('correctans');
$validate = $request->validate([
'ans' => "required",
'dbans' => 'required'
]);
$nextq = Session::get('nextq');
$nextq += 1;
if ($request->dbans == $request->ans) {
$correctans += 1;
} else {
$wrongans += 1;
}
Session::put("nextq", $nextq);
Session::put("wrongans", $wrongans);
Session::put("correctans", $correctans);
$i = 0;
$questions = question::all();
foreach ($questions as $question) {
$i++;
if ($questions->count() < $nextq) {
return view('pages.end');
}
if ($i == $nextq) {
// $question = Question::where('id', '>', $question->id)->orderBy('id')->first();
return view('pages.questions.quiz')->with(['question' => $question]);
}
}}
and this and this is a part of the view :
<form method="POST" action="/submitans">
#csrf
<h5 class="mt-1 ml-2">{{ $question->title }}</h5>
</div>
<div class="text-center">
<img src="{{ asset('storage/' . $question->image) }}" alt="image" class="rounded">
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" id="flexCheckDefault"
name="ans" checked="true" />
<label class="form-check-label" for="flexCheckDefault">{{ $question->reponse1 }}</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" id="flexCheckDefault"
name="ans" />
<label class="form-check-label" for="flexCheckDefault">{{ $question->reponse2 }}</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" id="flexCheckDefault"
name="ans" />
<label class="form-check-label" for="flexCheckDefault">{{ $question->reponse3 }}</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" id="flexCheckDefault"
name="ans" />
<label class="form-check-label" for="flexCheckDefault">{{ $question->reponse4 }}</label>
</div>
<input value="{{ $question->ans }}" style="visibility: hidden" name="dbans">
</div>
<div class="d-flex flex-row justify-content-between align-items-center p-3 bg-white">
<button class="btn btn-primary border-success align-items-center btn-success"
type="submit">Next<i class="fa fa-angle-right ml-2"></i></button>
and the routing is :
Route::get('/quiz',[QuestionController::class,'index']);
Route::any('/submitans', [QuestionController::class, 'submitans']);

How to send some data and image from AJAX to Controller in Laravel?

I'm a freshmen in the office and I was assigned by my boss to fix the code of the website that the developer is not in the company anymore. He used mostly AJAX to do things which I'm not used to it. I rarely use AJAX in my project, so I'm very very new about this.
From the old code, I'm trying to send an image with some data from an input form. I can console.log(form_data) to see its values, but I don't know why the content of image cannot be sent to Controller. It's getting 'null' and I can't store it.
Here is the code in input form
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">{{$head}}</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="input-form" class="needs-validation" novalidate method="POST" enctype="multipart/form-data" name="input-form">
{{ csrf_field() }}
<div class="form-horizontal">
<div class="form-group required">
<label class="col-sm-12 control-label" for="thai_name">{{trans('home.thai_name')}}</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="thai_name" name="thai_name" value="{{isset($user) ? $user->thai_name : ''}}" required/>
</div>
</div>
<div class="form-group required">
<label class="col-sm-12 control-label" for="eng_name">{{trans('home.eng_name')}}</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="eng_name" name="eng_name" value="{{isset($user) ? $user->eng_name : ''}}" required/>
</div>
</div>
<div class="form-group required">
<label class="col-sm-12 control-label" for="email">{{trans('home.email')}}</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="email" name="email" value="{{isset($user) ? $user->email : ''}}" required/>
</div>
</div>
<div class="form-group required">
<label class="col-sm-12 control-label" for="password">{{trans('home.password')}}</label>
<div class="col-sm-12">
<input type="password" id="password" class="form-control" required/>
</div>
</div>
<div class="form-group required">
<label class="col-sm-12 control-label" for="password_confirmation">{{trans('home.password_confirmation')}}</label>
<div class="col-sm-12">
<input type="password" id="password_confirmation" class="form-control" required/>
</div>
</div>
<div class="form-group col-sm-12">
<a class="btn-link" id="message" style="text-align: center;"></a>
</div>
<div class="form-group required">
<label class="col-sm-12 control-label" for="phone">{{trans('home.phone')}}</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="phone" name="phone" value="{{isset($user) ? $user->telephone : ''}}" required/>
</div>
</div>
<div class="form-group">
<label class="col-sm-12 control-label" for="fax">{{trans('home.fax')}}</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="fax" name="fax" value="{{isset($user) ? $user->fax : ''}}"/>
</div>
</div>
<div class="form-group required">
<label class="col-sm-12 control-label">{{trans('home.system_role')}}</label>
<div class="col-sm-12">
<div class="form-check form-check-inline">
<input class="form-check-input role" type="radio" id="admin" name="role" value="1"
{{isset($user) && $user->system_role_id == 1 ? 'checked' : ''}} required>
<label class="form-check-label" for="admin">ผู้ดูแลระบบ</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input role" type="radio" id="content_admin" name="role" value="2"
{{isset($user) && $user->system_role_id == 2 ? 'checked' : ''}} required>
<label class="form-check-label" for="content_admin">ผู้ดูแลข้อมูล</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input role" type="radio" id="user" name="role" value="3"
{{isset($user) && $user->system_role_id == 3 ? 'checked' : ''}} required>
<label class="form-check-label" for="user">ผู้ใช้งาน</label>
</div>
</div>
</div>
<div class="form-group required">
<label class="col-sm-12 control-label">{{trans('home.faction')}}</label>
<div class="col-sm-12">
<select id="faction" class="form-control">
#foreach($factions as $faction)
<option value="{{$faction->id}}" {{isset($user) && $user->faction_id == $faction->id ? 'selected' : ''}}>
{{trans('home.'.$faction->name)}}
</option>>
#endforeach
</select>
</div>
</div>
<div class="form-group required">
<label class="col-sm-12 control-label">{{trans('home.position')}}</label>
<div class="col-sm-12">
<select id="position" class="form-control">
#foreach($positions as $position)
<option value="{{$position->id}}" {{isset($user) && $user->position_id == $position->id ? 'selected' : ''}}>
{{trans('home.'.$position->name)}}
</option>>
#endforeach
</select>
</div>
</div>
<div class="form-group required">
<div class="col-sm-12">
<label class="control-label" for="photo">รูปถ่าย</label>
<input type="file" class="form-control-file" id="photo" name="photo" accept="image/*" required/>
</div>
</div>
<div class="form-group">
<label class="col-sm-12 control-label">{{trans('home.acting')}} / {{trans('home.past')}}</label>
<div class="col-sm-12">
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="acting" name="acting" {{isset($user) && $user->is_acting ? 'checked' : ''}}>
<label class="form-check-label" for="acting">{{trans('home.acting')}}</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="past" name="past" {{isset($user) && $user->is_past ? 'checked' : ''}}>
<label class="form-check-label" for="past">{{trans('home.past')}}</label>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-12" for="start">{{trans('home.start')}}</label>
<div class="col-sm-12">
<div class="input-group" id="start" name="start">
<input type="text" class="form-control" readonly="readonly"/>
<div class="input-group-append">
<span class="input-group-text input-group-addon">
<span class="fa fa-calendar"></span>
</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-12" for="end">{{trans('home.end')}}</label>
<div class="col-sm-12">
<div class="input-group" id="end" name="end">
<input type="text" class="form-control" readonly="readonly"/>
<div class="input-group-append">
<span class="input-group-text input-group-addon">
<span class="fa fa-calendar"></span>
</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="row col-sm-12 text-center">
<input type="button" class="btn btn-default" value="{{trans('home.save')}}"
onclick="{{$func}}"
/>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$('#start').datetimepicker({
sideBySide: true,
locale: 'th',
format: 'YYYY-MM-DD',
ignoreReadonly: true,
defaultDate: "{{isset($user) ? $user->start : ''}}"
});
$('#end').datetimepicker({
sideBySide: true,
locale: 'th',
format: 'YYYY-MM-DD',
ignoreReadonly: true,
defaultDate: "{{isset($user) ? $user->end : ''}}"
});
$('#password, #password_confirmation').on('keyup', function () {
if ( $('#password').val() == $('#password_confirmation').val() ) {
if ( $('#password').val() != '') {
$('#message').html('{{trans("home.password_match")}}').css('color', 'green');
} else {
$('#message').html('{{trans("home.password_null")}}').css('color', 'red');
$('#password').removeClass('valid').addClass('invalid');
$('#password_confirmation').removeClass('valid').addClass('invalid');
}
} else {
$('#message').html('{{trans("home.password_mismatch")}}').css('color', 'red');
$('#password').removeClass('valid').addClass('invalid');
$('#password_confirmation').removeClass('valid').addClass('invalid');
}
});
});
</script>
Here is the code in user.js where I'm using AJAX to send form_data contains image and some data
function addUser() {
var validate = validateUser("add");
if (validate.error == '') {
$('#modal1').modal({backdrop: "static"});
var form_data = {
thai_name: validate.thai_name,
eng_name: validate.eng_name,
email: validate.email,
password: validate.password,
password_confirmation: validate.password_confirmation,
telephone: $('#phone').val(),
fax: $('#fax').val(),
system_role_id: $('input[name=role]:checked').val(),
faction_id: $('#faction').val(),
position_id: $('#position').val(),
photo: $('#photo').val(),
photo_file: $('#photo').prop("files")[0],
is_acting: 0,
is_past: 0,
start: $('#start').data('date'),
end: $('#end').data('date'),
};
if ($('#acting').is(':checked')) {
form_data.is_acting = 1;
}
if ($('#past').is(':checked')) {
form_data.is_past = 1;
}
console.log(form_data);
$.ajax({
type: "post",
enctype: "multipart/form-data",
url: baseurl + "/admin/user/add",
data: form_data,
processData: false,
contentType: false,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function () {
$('#input-area').modal('hide');
listUser();
}
});
}
}
Here is some code in my controller
public function addUser(Request $request) {
$user = new User();
$user->thai_name = request()->thai_name;
$user->eng_name = request()->eng_name;
$user->email = request()->email;
$user->password = Hash::make(request()->password);
$user->telephone = request()->telephone;
$user->fax = request()->fax;
$user->system_role_id = request()->system_role_id;
$user->faction_id = request()->faction_id;
$user->position_id = request()->position_id;
// Store Profile Photo
$filename = "profile-photo-" . time() . "-name-" . basename(request()->photo);
request()->file('photo_file')->storeAs('', $filename, 'images');
$user->photo = $filename;
$user->is_acting = request()->is_acting;
$user->is_past = request()->is_past;
$user->start = request()->start;
$user->end = request()->end;
$user->save();
}
Which part I did wrong? Any ideas?
Please help me figure this out.
Thank you in advanced.

how to send data from the view to the controller In laravel

I'm doing a web application, and I get to a point where I can not move forward, I do not know how to do this, I'm starting with laravel so maybe the solution is very simple:
public function detalle($id){
// $nota = App\Nota::find($id);
//Aquí valida si existe sino redirije al 404
$producto = App\Producto::findOrFail($id);
$cantidad = 1;
return view('productos.detalle', compact('producto','cantidad'));
}
View:
<div class="card col-6 ">
<div class="card-body card-buy">
<h1 class="display-4 ">{{$producto->nombre}}</h1>
<p class="h3 mt-5">S/ {{$producto->precio}}</p>
<div class="form-inline">
<i class="fas fa-credit-card h1 mr-1"></i>
<p class="mt-2 "> <b>Metodo de pago:</b> A convenir</p>
</div>
<div class="form-inline">
<i class="fab fa-mailchimp ml-2 mr-2 h1"></i>
<p class="mt-2 "> <b>Envio:</b> Disponible a todo el pais</p>
</div>
<div class="form-inline ">
<div class="mt-n5 mr-2">
<b>Cantidad:</b>
</div>
<div class="def-number-input number-input safari_only">
<button onclick="this.parentNode.querySelector('input[type=number]').stepDown()" class="minus"></button>
<input readonly="readonly" class="quantity" min="1" max="{{$producto->stock}}" name="quantity" value="{{$cantidad}}" type="number">
<button onclick="this.parentNode.querySelector('input[type=number]').stepUp()" class="plus"></button>
</div>
<div class="mt-n5 ml-2">
<b class="text-decoration-none"> ( {{$producto->stock}} disponibles)</b>
</div>
</div>
Comprar
</div>
</div>
https://gyazo.com/febcd4c38cb3ef244e7424a3d92079a4
I already created the detail view of my product, and I put a button for the user to select the amount of products he wants, until there is everything right ...
But I want that number that the person chose to go to the next view, which is to confirm
https://gyazo.com/f56cf578808e75a0fab25eeffa8d2c5d
but that data {{$cantidad}} I do not know how to pass it to this new view I put the code:
Controller:
public function detallescompra($id){
$producto = App\Producto::findOrFail($id);
$total = 0;
$num1 = $producto->precio;
$num2 = $producto->stock;
$total = $num1 * $num2;
return view('productos.compra', compact('producto','total'));
}
and in the view:
<div class="container">
<div class="row" id="contenido">
<div class="col-md-8">
<div class="card">
<div class="card-header d-flex justify-content-between align-items-center">
<span>Revisa y Confirma</span>
Seguir viendo...
</div>
<div class="card-body">
#if ( session('mensaje') )
<div class="alert alert-success">{{ session('mensaje') }}</div>
#endif
<form method="POST" action="{{ route ('productos.comprafinal') }}">
#csrf
<label class="text-gray">Contacto y Envio:</label>
<div id="contenido">
<input type="name" name="usuario" placeholder="Nombre y Apellido" class="form-control mb-2" required />
<input type="email" name="email" placeholder="Email de contacto" class="form-control mb-2" required />
<input type="number" name="tlf" placeholder="Numero de telefono" class="form-control mb-2" />
<input type="street-address" name="direccion" placeholder="Direccion (Calle - #Casa - Referencia)" class="form-control mb-2" validate required />
<input type="text" name="id" placeholder="" class="form-control mb-2 d-none" value="{{$producto->id}}" />
<input type="text" name="timestamps" placeholder="" class="form-control mb-2 d-none" value="{{$producto->timestamp}}" />
<label class="text-gray">Producto:</label>
<input type="text" name="nombre" placeholder="Precio del Producto" class="form-control mb-2" value="{{$producto->nombre}}" readonly="readonly" />
<input type="text" name="precio" placeholder="Precio del Producto" class="form-control mb-2" value="Precio por unidad: S/ {{$producto->precio}}" readonly="readonly" id="valor1" />
<input type="text" name="cantidad" placeholder="Precio del Producto" class="form-control mb-2" value="Numero de productos: " readonly="readonly" id="valor2" />
<input type="text" name="" placeholder="Precio del Producto" class="form-control mb-2" value="Total a pagar: S/ {{$total}}" readonly="readonly" id="total" />
<button class="btn btn-success btn-block" type="submit">Comprar</button>
</div>
</form>
</div>
</div>
</div>
<div class="col-mod-4">
<div class="card" style="width: 18rem;">
<img src="{{$producto->img}}" class="card-img-top" alt="...">
</div>
</div>
</div>
I just need to spend that {{$cantidad}} in my view productos.compra, So far I have tried many things but nothing has given me even the minimum result
I'm new to this, I need help :(
GG :D
public function detallescompra(Request $request,$id){
$producto = App\Producto::findOrFail($id);
$cantidad = $request->input('cantidad');
$total = 0;
$num1 = $producto->precio;
$num2 = $cantidad;
$total = $num1 * $num2;
return view('productos.compra', compact('producto','total','cantidad'));
}
View:
<form action="{{ route('productos.compra-confirm', $producto) }}" method="POST">
#csrf
<div class="form-inline ">
<div class="mt-n5 mr-2">
<b>Cantidad:</b>
</div>
<div class="def-number-input number-input safari_only">
<button type="button" onclick="this.parentNode.querySelector('input[type=number]').stepDown()" class="minus"></button>
<input readonly="readonly" class="quantity" min="1" max="{{$producto->stock}}" name="cantidad" value="{{$cantidad}}" type="number">
<button type="button" onclick="this.parentNode.querySelector('input[type=number]').stepUp()" class="plus"></button>
</div>
<div class="mt-n5 ml-2">
<b class="text-decoration-none"> ( {{$producto->stock}} disponibles)</b>
</div>
</div>
<button type="submit" class=" align-bottom btn btn-success btn-lg btn-block ">Comprar</button>
</div>
</div>
</form>
routes web:
Route::post('/comprar/{id}', 'HomeController#detallescompra')->name('productos.compra-confirm');

Checkout Form isn't Submitting

I'm trying to submit the checkout form, but it is not submitting. It has values of products form cart (product name, code, price) and currently entered user data, and screenshot of DB table (orders) https://ibb.co/bbBHCky ...... any solution to resolve it,..........,,,,,,,,.
checkout.blade.php
<ul class="list-group mb-3">
<?php $total_amount = 0; ?>
#foreach($userCart as $cart)
<li class="list-group-item d-flex justify-content-between lh-condensed">
<div>
<h6 class="my-0">{{ $cart->product_name }}</h6>
<small class="text-muted">Quantity: {{ $cart->quantity }}</small>
<small class="text-muted" style="display: none;">{{ $cart->product_code }}</small>
<small class="text-muted" style="display: none;">{{ $cart->product_id }}</small>
</div>
<span class="text-muted">Rs {{ $cart->price }}</span>
</li>
#endforeach
<li class="list-group-item d-flex justify-content-between">
<span>Total (PKR)</span>
<strong>{{ $total }}</strong>
</li>
</ul>
<form method="post" action="{{ url('/checkout') }}" class="needs-validation" novalidate>{{ csrf_field() }}
<div class="row">
<div class="col-md-6 mb-3">
<label for="firstName">Name</label>
<input type="text" name="name" class="form-control" id="firstName" placeholder="name" value="" required
style="border: 1px solid black !important;">
<div class="invalid-feedback">
Valid first name is required.
</div>
</div>
</div>
<div class="mb-3">
<label for="email">Email </label>
<input type="email" name="email" class="form-control" id="email" placeholder="you#example.com"
required="required" style="border: 1px solid black !important;">
<div class="invalid-feedback">
Please enter a valid email address for shipping updates.
</div>
</div>
<div class="mb-3">
<label for="address">Address</label>
<input type="text" name="address" class="form-control" id="address" placeholder="1234 Main St" required
style="border: 1px solid black !important;">
<div class="invalid-feedback">
Please enter your shipping address.
</div>
</div>
<div class="row">
<div class="col-md-5 mb-3">
<label for="country">Country</label>
<select name="country" class="custom-select d-block w-100" id="country" required>
<option value="">Choose...</option>
<option value="usa">United States</option>
</select>
<div class="invalid-feedback">
Please select a valid country.
</div>
</div>
<div class="col-md-4 mb-3">
<label for="state">State</label>
<select name="state" class="custom-select d-block w-100" id="state" required>
<option value="">Choose...</option>
<option value="cal">California</option>
</select>
<div class="invalid-feedback">
Please provide a valid state.
</div>
</div>
<div class="col-md-5 mb-3">
<label for="country">City</label>
<select name="city" class="custom-select d-block w-100" id="country" required>
<option value="">Choose...</option>
<option value="lhr">United States</option>
</select>
<div class="invalid-feedback">
Please select a valid country.
</div>
</div>
<div class="col-md-3 mb-3">
<label for="zip">Zip</label>
<input type="text" name="zipcode" class="form-control" id="zip" placeholder="" required
style="border: 1px solid black !important;">
<div class="invalid-feedback">
Zip code required.
</div>
</div>
<div class="col-md-5 mb-3">
<label for="zip">Mobile</label>
<input type="text" name="mobile" class="form-control" id="zip" placeholder="" required
style="border: 1px solid black !important;">
<div class="invalid-feedback">
mobile no required.
</div>
</div>
</div>
<button class="btn btn-primary btn-lg btn-block" type="submit" style="background-color: black;">Place Order</button>
</form>
ProductsController
public function placeOrder(Request $request)
{
if ($request->isMethod('post')) {
$data = $request->all();
$session_id = Session::get('session_id');
if (empty($session_id)) {
$session_id = str_random(40);
Session::put('session_id', $session_id);
}
$order = new Order;
$order->id = $id;
$order->name = $name;
$order->email = $email;
$order->address = $address;
$order->country = $country;
$order->state = $state;
$order->city = $city;
$order->zipcode = $zipcode;
$order->mobile = $mobile;
$order->product_id = $product_id;
$order->product_code = $product_code;
$order->product_name = $product_name;
$order->product_price = $product_price;
$order->product_quantity = $qty;
$order->order_status = "New";
$order->grand_total = $data['grand_total'];
$order->save();
return view('products.checkout');
}
}
Route
Route::match(['get','post'],'/place-order','ProductsController#placeOrder');
change form action to
<form method="post" action="{{ url('place-order') }}" class="needs-validation" novalidate>
and remove space from route: '/place- order'
Route::match(['get','post'],'/place-order','ProductsController#placeOrder');

Laravel 5.2 cannot update record

I cannot seem to update my record.
My controller
public function add()
{
return view('cars.add');
}
public function edit($id)
{
$car = Cars::whereId($id)->firstOrFail();
return view('cars.edit', compact('car'));
}
public function store(CarFormRequest $request)
{
$car = new Cars(array(
'name' => $request->get('name'),
'color_id' => $request->get('color')
));
$car->save();
$car->position_id = $car->id;
$car->save();
session()->flash('status', 'Successfully Added a Car!');
return view('cars.add');
}
public function update($id, CarFormRequest $request)
{
$car = car::whereId($id)->firstOrFail();
$car->name = $request->get('name');
$car->color_id = $request->get('color');
if($request->get('status') != null) {
$car->status = 0;
} else {
$car->status = 1;
}
$car->save();
return redirect(action('CarController#edit', $car->id))->with('status', 'The ticket '.$id.' has been updated!');
}
my routes:
Route::get('/', 'PagesController#home');
Route::get('/about', 'PagesController#about');
Route::get('/contact', 'PagesController#contact');
Route::get('/cars', 'CarsController#index');
Route::get('/cars/edit/{id?}', 'CarsController#edit');
Route::post('/cars/edit/{id?}', 'CarsController#update');
Route::get('/cars/add', 'CarsController#add');
Route::post('/cars/add', 'CarsController#store');
here is my view:
<div class="container col-md-8 col-md-offset-2">
<div class="well well bs-component">
<form class="form-horizontal" method="post">
<input type="hidden" name="_token" value="{!! csrf_token() !!}">
<input type="text" id="color_id" name="color_id" value="{!! $car->color_id !!}">
<fieldset>
<legend>Edit Car Information</legend>
<div class="form-group">
<label for="title" class="col-lg-2 control-label">Car Name</label>
<div class="col-lg-10">
<input type="text" value="{{ $car->name }}" class="form-control" id="name" placeholder="Car Name">
</div>
</div>
<div class="form-group">
<label for="title" class="col-lg-2 control-label">Car Color</label>
<div class="col-lg-10">
<div class="btn-group" data-toggle="buttons">
<label id="opt1" class="btn btn-primary">
<input type="radio" name="color" id="option1" autocomplete="off"> Red
</label>
<label id="opt2" class="btn btn-primary">
<input type="radio" name="color" id="option2" autocomplete="off"> Blue
</label>
<label id="opt3" class="btn btn-primary">
<input type="radio" name="color" id="option3" autocomplete="off"> Yellow
</label>
<label id="opt4" class="btn btn-primary">
<input type="radio" name="color" id="option4" autocomplete="off"> Green
</label>
<label id="opt5" class="btn btn-primary">
<input type="radio" name="color" id="option5" autocomplete="off"> Black
</label>
<label id="opt6" class="btn btn-primary">
<input type="radio" name="color" id="option6" autocomplete="off"> White
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button class="btn btn-default">Cancel</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
The $id variable in whereIn must be array and you need to specify the database column too. This should be like -
public function edit($id)
{
$car = Cars::whereId('id', [$id])->firstOrFail();
return view('cars.edit', compact('car'));
}
Change all occurrence of
$car = car::whereId($id)->firstOrFail();

Resources