am working on a laravel project and I am working on a user update profile, I am getting an error when updating and I can't figure out the solution.
below is the error I am getting
Target class [App\Http\Controllers\UpdateProfileRequest] does not exist.
below is my route in web.php
Route::get('users/edit', 'UserController#edit')->name('users.edit');
Route::put('users/update', 'UserController#update')->name('users.update');
below is UserController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UserController extends Controller
{
//
public function edit()
{
return view('users.edit')->with('user', auth()->user());
}
public function update(UpdateProfileRequest $request)
{
$user = auth()->user();
$user->update([
'name' => $request->name,
'organization' => $request->organization,
'email' => $request->email,
'password' => $request->password
]);
return redirect()->back;
}
}
below is my UpdateProfileRequest
<?php
namespace App\Http\Requests\User;
use Illuminate\Foundation\Http\FormRequest;
class UpdateProfileRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name'=>'required',
'organization'=>'required',
'email'=>'required',
'password'=>'required'
];
}
}
below is the edit.blade.php view
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<p class="card-text"><img src="{{ asset('img/logo1.jpg') }}" width="60" height="50" class="mx-auto d-block" alt="logo1"></p>
<hr style="width:50%", size="2", color=3490dc>
<div class="card">
<div style="text-align: center; background-color:#3490dc; color:white;" class="card-header"><i class="fa fa-user-circle" aria-hidden="true"></i> {{ __('My Profile') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('users.update') }}">
#csrf
#method('PUT')
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right"><i class="fa fa-user" style="color:#3490dc;"></i> {{ __('Name') }}</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control #error('name') is-invalid #enderror" name="name" value="{{ $user->name }}" required autocomplete="name" autofocus>
</div>
</div>
<div class="form-group row">
<label for="organization" class="col-md-4 col-form-label text-md-right"><i class="fa fa-building-o" style="color:#3490dc;"></i> {{ __('Organization') }}</label>
<div class="col-md-6">
<input id="organization" type="text" class="form-control #error('organization') is-invalid #enderror" name="organization" value="{{ $user->organization }}" required autocomplete="organization" autofocus>
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right"><i class="fa fa-envelope" style="color:#3490dc;"></i> {{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ $user->name }}" required autocomplete="email">
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right"><i class="fa fa-key" style="color:#3490dc;"></i> {{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="new-password">
</div>
</div>
<div class="form-group row">
<label for="password-confirm" class="col-md-4 col-form-label text-md-right"><i class="fa fa-key" style="color:#3490dc;"></i> {{ __('Confirm Password') }}</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required autocomplete="new-password">
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Update') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<br/>
#include('footer')
#endsection
below is the link to the view in app.blade.php
<a class="dropdown-item" href="{{ route('users.edit') }}"
>
{{ __('My Profile') }}
</a>
<form id="edit-form" action="{{ route('users.edit') }}" style="display: none;">
#csrf
</form>
I will appreciate any help thanks in advance
You're missing a using.
Add use UpdateProfileRequest; at the top.
(this might not be the correct path, try hovering UpdateProfileRequest and looking for an Import class button)
You must use it on top of UserController class:
use App\Http\Requests\UpdateProfileRequest;
Related
Does anyone know, How to resolve this issue of the crashed javascript script?
I am using 2 checkboxes to load some DOM.
1st checkbox is to expand textarea with the CKEditor script which is loaded with the JS but I have a wire model to send data to the controller.
Here is HTML for 1st checkbox:
<div class="form-group mt-25 d-flex flex-row">
<label class="checkbox-container form-group__label">
{{ __('Extended description') }}
<input type="checkbox" name="extended-description-checkbox" id="extended-description-checkbox" class="checkbox">
<span class="checkmark"></span>
</label>
</div>
<div class="form-group mt-25 cke d-none" id="extended-description-checkbox-div">
<label class="form-group__label" for="extended-description">{{ __('Extended description') }}</label>
<textarea wire:ignore.self wire:model.debounce.250ms.defer="extendedDescription" name="extended-description" id="extended-description" cols="30" rows="10"></textarea>
</div>
2nd checkbox is also handled with the JS and has a temporary URL method since the expanded DOM element should contain uploaded images for the gallery.
Here is HTML of the 2nd checkbox:
<div class="form-group mt-25 d-flex flex-row">
<label class="checkbox-container form-group__label">
{{ __('Use default images') }}
<input type="checkbox" name="use-default-images" id="use-default-images" class="checkbox">
<span class="checkmark"></span>
</label>
</div>
<div class="d-none" id="use-default-images-div">
<div class="form-group mt-25">
<label class="form-group__label">{{ __('Service images') }}</label>
<div class="form-group__uploaded-images">
#if ($additionalImages)
#foreach($additionalImages as $image)
<img src="{{ $image->temporaryUrl() }}" alt="Temporary image">
#endforeach
#endif
</div>
</div>
<div class="custom-file ml-auto">
<button type="button" class="ml-auto styled-link">{{ __('Add images') }}</button>
<div class="row mt-25">
<div class="col-4 col-md-8"></div>
<div class="col-8 col-md-4">
<input wire:ignore.self wire:model.defer="additionalImages" type="file" multiple>
#error('images.*') {{ $message }} #enderror
</div>
</div>
</div>
</div>
Here are the scripts for expanding of the both DOM elements:
const extendedCheckbox = document.querySelector('#extended-description-checkbox');
const extendedDiv = document.querySelector('#extended-description-checkbox-div');
extendedCheckbox.addEventListener('change', function() {
if(extendedCheckbox.checked) {
extendedDiv.classList.remove('d-none');
} else {
extendedDiv.classList.add('d-none');
}
});
const defaultImagesCheckbox = document.querySelector('#use-default-images');
const defaultImagesDiv = document.querySelector('#use-default-images-div');
defaultImagesCheckbox.addEventListener('change', function() {
if(defaultImagesCheckbox.checked) {
defaultImagesDiv.classList.remove('d-none');
} else {
defaultImagesDiv.classList.add('d-none');
}
});
I'm developing a web app and currently coding a form. For some reason, even after filling up the form, it does not submit at first, I have to refresh the page for it to submit to the back-end.
Here's the code for the form:
#extends('layout.admin')
#section('styles')
<link rel="stylesheet" href="{{ asset('css/vendor/bootstrap-float-label.min.css') }}">
<link rel="stylesheet" type="text/css" href="{{ asset('css/vendor/select2.min.css')}}">
<link rel="stylesheet" type="text/css" href="{{ asset('css/vendor/select2-bootstrap.min.css')}}">
#endsection
#section('content')
#if (session()->has('success'))
<div class="alert alert-success rounded" role="alert">{{ session('success') }}</div>
#endif
#if(session()->has('error'))
<div class="alert alert-danger rounded" role="alert">{{ session('error') }}</div>
#endif
<form method="post" id="form" action="{{ isset($cliente) ? route('admin.clientes.update', $cliente) : route('admin.clientes.inserir') }}" class="form bv-form" enctype="multipart/form-data" novalidate>
#csrf
#if(isset($cliente))
#method('PUT')
#endif
<div class="container">
<div class="row">
<div class="col-md-7">
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-2 form-group has-float-label position-relative error-l-50">
<label for="tipo-cliente">Tipo Cliente: </label> <br>
<input type="radio" name="tipo" id="p_fisica" value="1" #if(isset($cliente) && $cliente->tipo === 1) checked #endif> Pessoa Fisica <br>
<input type="radio" name="tipo" id="p_juridica" value="2" #if(isset($cliente) && $cliente->tipo === 2) checked #endif> Pessoa Juridica
</div>
<div class="col form-group position-relative error-l-50 has-float-label" id="div_nome">
<label for="nome">Nome</label>
<input type="text" id="nome" name="nome" class="form-control" value="{{ isset($cliente) ? $cliente->nome : old('nome') }}">
</div>
<div class="col form-group position-relative error-l-50 has-float-label" id="div_cpf">
<label for="cpf">CPF</label>
<input type="text" name="cpf" id="cpf" class="form-control cpf" value="{{ isset($cliente) ? $cliente->cpf : old('cpf') }}">
</div>
<div class="col-md-2 form-group has-float-label position-relative error-l-50" id="div_sexo">
<label for="sexo">Sexo</label><br>
<input type="radio" name="sexo" id="sexo_masc" value="1" #if(isset($cliente) && $cliente->sexo === 1) checked #endif> Masculino <br>
<input type="radio" name="sexo" id="sexo_fem" value="2" #if(isset($cliente) && $cliente->sexo === 1) checked #endif> Feminino
</div>
<div class="col has-float-label form-group position-relative error-l-50 display-invisible" id="div_cnpj">
<label for="cnpj">CNPJ</label>
<input type="text" name="cnpj" id="cnpj" class="form-control cnpj" value="{{ isset($cliente) ? $cliente->cnpj : old('cnpj') }}" onkeyup="isValidCNPJ(this)">
</div>
<div class="col form-group position-relative error-l-50 has-float-label display-invisible" id="div_razao">
<label for="razao_social">Razao Social</label>
<input type="text" name="razao_social" class="form-control" id="razao_social" value="{{ isset($cliente) ? $cliente->razao_social : old('razao_social') }}">
</div>
</div> <!-- row end -->
<div class="row">
<div class="col-md-3 form-group position-relative error-l-50 has-float-label">
<label for="empresa_filial">Empresa Filial: </label>
<select name="empresa_filial" class="form-control select2-single">
#foreach($empresas as $empresa)
<option value="{{$empresa->id}}" #if(isset($cliente) && $cliente->empresa_filial === $empresa->id) selected #endif>{{$empresa->nome_empresa}}</option>
#endforeach
</select>
</div>
<div class="col-md-4 has-float-label form-group position-relative error-l-50">
<label for="email">Email</label>
<input type="email" name="email" class="form-control" value="{{ isset($cliente) ? $cliente->email : old('email') }}">
</div>
<div class="col-md-2 has-float-label form-group position-relative error-l-50">
<label for="cod_pais_2">Pais</label>
<input type="text" name="cod_pais_2" class="form-control cod_pais_2" required value="+55" value="{{ isset($cliente) ? $cliente->cod_pais_2 : old('cod_pais_2') }}">
</div>
<div class="col-md-3 has-float-label form-group position-relative error-l-50">
<label for="telefone">Telefone</label>
<input type="text" name="telefone" class="form-control telefone" id="telefone" value="{{ isset($cliente) ? $cliente->telefone : old('telefone') }}">
</div>
</div> <!-- row end -->
<div class="row">
<div class="col-md-2 has-float-label form-group position-relative error-l-50">
<label for="cep">CEP</label>
<input type="text" name="cep" class="form-control cep" id="cep" name="cep" required value="{{ isset($cliente) ? $cliente->cep : old('cep') }}">
</div>
<div class="col-md-5 has-float-label form-group position-relative error-l-50">
<label for="endereco">Endereco</label>
<input type="text" name="endereco" class="form-control" required id="endereco" value="{{ isset($cliente) ? $cliente->endereco : old('endereco') }}">
</div>
<div class="col-md-2 has-float-label form-group position-relative error-l-50">
<label for="cod_pais_1">Pais</label>
<input type="text" name="cod_pais_1" class="form-control cod_pais_1" required value="+55" value="{{ isset($cliente) ? $cliente->cod_pais_1 : old('cod_pais_1') }}">
</div>
<div class="col-md-3 has-float-label form-group position-relative error-l-50">
<label for="telefone">Celular</label>
<input type="text" name="celular" class="form-control celular" required value="{{ isset($cliente) ? $cliente->celular : old('celular') }}">
</div>
</div> <!-- row end -->
<div class="row">
<div class="col has-float-label form-group position-relative error-l-50">
<label for="complemento">Complemento</label>
<input type="text" name="complemento" required class="form-control" id="complemento" value="{{ isset($cliente) ? $cliente->complemento : old('complemento') }}">
</div>
<div class="col has-float-label form-group position-relative error-l-50">
<label for="ponto_referencia">Ponto de Referencia</label>
<input type="text" name="ponto_referencia" class="form-control" id="ponto_referencia" value="{{ isset($cliente) ? $cliente->ponto_referencia : old('ponto_referencia') }}">
</div>
<div class="col has-float-label form-group position-relative error-l-50">
<label for="bairro">Bairro</label>
<input type="text" name="bairro" class="form-control" required id="bairro" value="{{ isset($cliente) ? $cliente->bairro : old('bairro') }}">
</div>
</div><!-- row end -->
<div class="row">
<div class="col has-float-label form-group position-relative error-l-50">
<label for="cidade">Cidade</label>
<input type="text" name="cidade" required id="cidade" class="form-control" value="{{ isset($cliente) ? $cliente->cidade : old('cidade') }}">
</div>
<div class="col has-float-label form-group position-relative error-l-50">
<label for="uf">Estado</label>
<select class="form-control select2-single" name="uf" required>
<option value="" selected>Selecione</option>
#foreach(\App\Helpers\Helpers::estados() as $estado => $nome)
<option value="{{ $estado }}" #if(isset($cliente) && $cliente->uf === $estado) selected #endif>{{ $nome }}</option>
#endforeach
</select>
</div>
<div class="col has-float-label form-group position-relative error-l-50">
<label for="pais">Pais</label>
<select class="form-control select2-single" required id="pais" name="pais" data-width="100%">
#foreach(\App\Helpers\Helpers::paises() as $pais)
<option value="{{ $pais['nome'] }}" #if(isset($cliente) && $cliente->pais === $pais) selected #endif>{{ $pais['nome'] }}</option>
#endforeach
</select>
</div>
</div><!-- row end -->
<div class="row">
<div class="col has-float-label form-group position-relative error-l-50">
<label for="observacao">Observacao</label>
<input type="text" name="observacao" class="form-control" id="observacao" value="{{ isset($cliente) ? $cliente->observacao : old('observacao') }}">
</div>
</div><!-- row end -->
</div>
</div>
</div>
<div class="col-md-5">
<div class="card" style="padding-bottom: 2px">
<div class="card-body">
<div class="row">
<h3 style="margin-left:8px">Informacoes de Cobranca</h3>
</div><!-- row end -->
<div class="row">
<input type="checkbox" name="reciclar_info" id="client-check" style="margin-left:8px" onchange="chargingFields()">
<span style="margin: 10px">Usar as mesmas informacoes de endereco para cobranca</span>
<hr class="style-six"> <br>
</div>
<div class="row">
<div class="col-md-4 has-float-label form-group position-relative error-l-50">
<label for="cobranca_cnpj">CNPJ</label>
<input type="text" name="cobranca_cnpj" onkeyup="isValidCobrancaCNPJ()" class="form-control cnpj" id="cobranca_cnpj" value="{{ isset($cliente) ? $cliente->cobranca_cnpj : old('cobranca_cnpj') }}">
</div>
<div class="col-md-8 has-float-label form-group position-relative error-l-50">
<label for="cobranca_razao_social">Razao Social</label>
<input type="text" name="cobranca_razao_social" class="form-control" id="cobranca_razao_social" value="{{ isset($cliente) ? $cliente->cobranca_razao_social : old('cobranca_razao_social') }}">
</div>
</div><!-- row end -->
<div class="row">
<div class="col-md-4 has-float-label form-group position-relative error-l-50">
<label for="cobranca_cep">CEP</label>
<input type="text" name="cobranca_cep" class="form-control cep" id="cobranca_cep" value="{{ isset($cliente) ? $cliente->cobranca_cep : old('cobranca_cep') }}">
</div>
<div class="col-md-8 has-float-label form-group position-relative error-l-50">
<label for="cobranca_endereco">Endereco</label>
<input type="text" name="cobranca_endereco" class="form-control" id="cobranca_endereco" value="{{ isset($cliente) ? $cliente->cobranca_endereco : old('cobranca_endereco') }}">
</div>
</div>
<div class="row">
<div class="col has-float-label form-group position-relative error-l-50">
<label for="cobranca_complemento">Complemento</label>
<input type="text" name="cobranca_complemento" class="form-control" id="cobranca_complemento" value="{{ isset($cliente) ? $cliente->cobranca_complemento : old('cobranca_complemento') }}">
</div>
<div class="col has-float-label form-group position-relative error-l-50">
<label for="cobranca_ponto_referencia">Ponto de Referencia</label>
<input type="text" name="cobranca_ponto_referencia" id="cobranca_ponto_referencia" class="form-control" value="{{ isset($cliente) ? $cliente->cobranca_ponto_referencia : old('cobranca_ponto_referencia') }}">
</div>
<div class="col has-float-label form-group position-relative error-l-50">
<label for="cobranca_bairro">Bairro</label>
<input type="text" name="cobranca_bairro" class="form-control" id="cobranca_bairro" value="{{ isset($cliente) ? $cliente->cobranca_bairro : old('cobranca_bairro') }}">
</div>
</div>
<div class="row">
<div class="col has-float-label form-group position-relative error-l-50">
<label for="cobranca_cidade">Cidade</label>
<input type="text" name="cobranca_cidade" id="cobranca_cidade" class="form-control" value="{{ isset($cliente) ? $cliente->cobranca_cidade : old('cobranca_cidade') }}">
</div>
<div class="col has-float-label form-group position-relative error-l-50">
<label for="cobranca_uf">Estado</label>
<select class="form-control select2-single" name="cobranca_uf" id="cobranca_uf">
<option value="" selected>Selecione</option>
#foreach(\App\Helpers\Helpers::estados() as $estado => $nome)
<option value="{{ $estado }}"
#if(isset($cliente) && $cliente->cobranca_uf === $estado) selected #endif>{{ $nome }}</option>
#endforeach
</select>
</div>
<div class="col has-float-label form-group position-relative error-l-50">
<label for="cobranca_pais">Pais</label>
<select class="form-control select2-single" name="cobranca_pais" id="cobranca_pais">
#foreach(\App\Helpers\Helpers::paises() as $pais)
<option value="{{ $pais['nome'] }}" #if(isset($cliente) && $cliente->cobranca_pais === $pais) selected #endif>{{ $pais['nome'] }}</option>
#endforeach
</select>
</div>
</div><!-- row end -->
<div class="row">
<div class="col has-float-label form-group position-relative error-l-50">
<label for="cobranca_observacao">Observacao</label>
<input type="text" name="cobranca_observacao" class="form-control" id="cobranca_observacao" value="{{ isset($cliente) ? $cliente->cobranca_observacao : old('cobranca_observacao') }}">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-1">
<button type="submit" id="save-button" class="btn btn-primary float-left" style="margin-top: 10px">
#if(isset($cliente))
Salvar
#else
Adicionar
#endif
</button>
</div>
</div><!-- row end -->
</div>
</form>
#endsection
#section('js')
<script src="{{ asset('js/vendor/jquery.validate/jquery.validate.min.js') }}"></script>
<script src="{{ asset('js/vendor/jquery.validate/additional-methods.min.js') }}"></script>
<script src="{{ asset('js/vendor/select2.full.js') }}"></script>
<script>
const addressApiUrl = "{{ route('pega.endereco') }}";
</script>
<script src="{{ asset('js/cliente_form.js') }}"></script>
<script type="text/javascript">
var sent = false;
function isValidCobrancaCNPJ() {
var strCNPJ = $("#cobranca_cnpj").val();
console.log(strCNPJ);
// Caso o CEP não esteja nesse formato ele é inválido!
var objER = /^[0-9]{14}$/;
strCNPJ = Trim(strCNPJ);
if(strCNPJ.length > 0) {
if(objER.test(strCNPJ) && !sent) {
sent = true;
formReadOnly(true);
$.ajax({
method: 'POST',
url: "{{ route('pega.cnpj.interno') }}",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: {cnpj: strCNPJ},
success: function (data) {
if(!data.error) {
$.notify({
// options
message: 'CNPJ verificado!'
},{
// settings
type: 'success'
});
$('#cobranca_razao_social').val(data.razao_social);
$('#cobranca_cep').val(data.cep);
$('#cobranca_endereco').val(data.endereco);
$('#cobranca_bairro').val(data.bairro);
$('#cobranca_cidade').val(data.cidade);
$('#cobranca_uf').val(data.uf);
$('#cobranca_endereco').focus();
sent = false;
$('#form').bootstrapValidator('destroy');
$('#form').data('bootstrapValidator', null);
$('#form').bootstrapValidator();
}else{
$.notify({
// options
message: data.msg
},{
// settings
type: 'danger'
});
sent = false;
}
formReadOnly(false);
},
error: function (msg) {
sent = false;
formReadOnly(false);
}
});
}
}
}
function Trim(strTexto)
{
// Substitúi os espaços vazios no inicio e no fim da string por vazio.
return strTexto.replace(/\D/g, "");
}
function isValidCNPJ() {
var strCNPJ = $("#cnpj").val();
console.log(strCNPJ);
// Caso o CEP não esteja nesse formato ele é inválido!
var objER = /^[0-9]{14}$/;
strCNPJ = Trim(strCNPJ);
if(strCNPJ.length > 0)
{
if(objER.test(strCNPJ) && !sent)
{
sent = true;
formReadOnly(true);
$.ajax({
method: 'POST',
url: "{{ route('pega.cnpj.interno') }}",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: {cnpj: strCNPJ},
success: function (data)
{
if(!data.error)
{
$.notify({
// options
message: 'CNPJ verificado!'
},{
// settings
type: 'success'
});
$('#razao_social').val(data.razao_social);
$('#cep').val(data.cep);
$('#endereco').val(data.endereco);
$('#bairro').val(data.bairro);
$('#cidade').val(data.cidade);
$('#uf').val(data.uf);
$('#endereco').focus();
sent = false;
$('#form').bootstrapValidator('destroy');
$('#form').data('bootstrapValidator', null);
$('#form').bootstrapValidator();
}else{
$.notify({
// options
message: data.msg
},{
// settings
type: 'danger'
});
sent = false;
}
formReadOnly(false);
},
error: function (msg) {
sent = false;
formReadOnly(false);
}
});
}
}
}
</script>
#endsection
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Empresa;
use App\Models\Cliente;
class ClienteController extends Controller
{
public function index() {
$data['clientes'] = Cliente::all();
return view('admin.clientes.index', $data);
}
public function addCliente() {
$data['empresas'] = Empresa::all();
return view('admin.clientes.cadastro',$data);
}
public function insert(Request $request) {
$cliente = new Cliente;
$cliente->empresa_filial = $request->empresa_filial;
$cliente->tipo = $request->tipo;
$cliente->email = $request->email;
if ($request->tipo == 1) {
$cliente->nome = $request->nome;
$cliente->cpf = $request->cpf;
$cliente->cnpj = $cliente->razao_social = "";
} else {
$cliente->cnpj = $request->cnpj;
$cliente->razao_social = $request->razao_social;
$cliente->nome = $cliente->cpf = "";
}
//had to resume code due to body limitations, but basically what is above for other fields
$cliente->save();
return redirect()->back()->with(['success' => 'Cliente cadastrado com sucesso!']);
}
public function update($identificacao, Request $request) {
$cliente->save();
}
}
I'm currently using Laravel as a framework and have tried everything (#csrf, csrf_field(), adding a token via hidden input), nothing works, I'm lost.
Also, by checking the browser's network activity, POST methods for getting information such as address are working fine inside the form, only problem being the submit button.
EDIT: The routes:
Route::prefix('clientes')->group(function() {
Route::view('/1/detalhes', 'admin.clientes.detalhes')->name('admin.clientes.detalhes');
Route::get('/', 'ClienteController#index')->name('admin.clientes.index');
Route::get('/cadastro', 'ClienteController#addCliente')->name('admin.clientes.cadastro');
Route::get('/atualizar/{cliente}', 'ClienteController#atualizarCliente')->name('admin.clientes.atualizar');
Route::get('/{cliente}', 'ClienteController#delete')->name('admin.clientes.delete');
Route::put('/atualizar/{cliente}', 'ClienteController#update')->name('admin.clientes.update');
Route::post('/cadastro', 'ClienteController#insert')->name('admin.clientes.inserir');
});
I am trying to store some data in to the database. I have NewMember form this form will have data to be store in 3 tables users, restaurants, and addresses. It is showing the error MethodNotAllowedHttpException in RouteCollection.php line 218:. If I use an insert query with default values it will insert it successfully.
this is NewMember form
#extends('layouts.app')
#section('content')
<style>
body {
background-color: #fff0e6;
}
</style>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">
<h1><u><font color="990000" ;>Register new restaurant</font></u></h1>
</div>
<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="/restaurantmenus/">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label for="name" class="col-md-4 control-label">Restaurant name</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" name="name"
value="{{ old('name') }}">
</div>
</div>
<div class="form-group">
<label for="address" class="col-md-4 control-label">Address</label>
<div class="col-md-6">
<label for="name" class="col-md-4 control-label">City</label>
<select name="city" style="width: 150px" id="city" class="form-control">
<option value="Damascus">Damascus</option>
</select>
<br>
<label for="name" class="col-md-4 control-label">Region</label>
<select name="region" style="width: 150px" id="region" class="form-control">
<option value="111">111</option>
<option value="222">222</option>
</select>
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">Telephone</label>
<div class="col-md-6">
<input id="Telephone" type="text" class="form-control" name="Telephone"
value="{{ old('Telephone') }}">
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">About your restaurant</label>
<div class="col-md-6">
<textarea id="description" rows="4" cols="50" name="description"
value="{{ old('description') }}"
placeholder="Enter text here..." class="form-control"></textarea>
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">Email</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email"
value="{{ old('email') }}">
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">Username</label>
<div class="col-md-6">
<input id="username" type="text" class="form-control" name="username"
value="{{ old('username') }}">
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password"
value="{{ old('password') }}">
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">Confirm password</label>
<div class="col-md-6">
<input id="password2" type="password" class="form-control" name="password2"
value="{{ old('password2') }}">
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">Kitchen</label>
<div class="col-md-6">
<select name="kitchen" id="kitchen" class="form-control">
<option value="111">111</option>
<option value="222">222</option>
</select>
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">Working time</label>
<div class="col-md-6">
<label for="name" class="col-md-4 control-label">Open</label>
<input id="open" style="width: 150px" type="time" class="form-control" name="open"
value="{{ old('open') }}">
<br>
<label for="name" class="col-md-4 control-label">Close</label>
<input id="close" style="width: 150px" type="time" class="form-control" name="close"
value="{{ old('close') }}">
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">Delivery</label>
<label for="name">Yes</label>
<input id="delivery" type="checkbox" style="float: left;" name="delivery"
value="{{ old('delivery') }}">
<input id="price" style="width: 150px" style="float: left;" placeholder="Delivery price"
type="text" name="price" value="{{ old('price') }}">
</div>
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary"
style="background:#990000; border-color:#990000" ;>
<i class="fa fa-btn fa-user"></i> Register
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<br>
<br>
<footer>
#extends('layouts.footer')
</footer>
#endsection
this is the models
restaurant model it has one relationship with the addresses table (the restaurant has many addresses)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class restaurant extends Model
{
//
protected $fillable=['name','telephone' ,'description','delivery','DeliveryPrice','ownerName','ownerPhone', 'kitchen','open','close'];
public function addresses(){
return $this->hasMany('App/address');
}
}
?>
user model
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $table = 'users';//add
protected $fillable = [
'name', 'username','email', 'password','phone',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function restaurant(){
return $this->hasMany('App/restaurant');
}
}
}
addresses model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class address extends Model
{
//
protected $fillable=[
'city','region'
];
}
the controller
{
namespace App\Http\Controllers;
use App\address;
use App\restaurant;
use App\User;
use Illuminate\Http\Request;
use App\restaurant as restaurantAlias;
use App\Http\Requests;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use phpDocumentor\Reflection\DocBlock\Tags\Uses;
class restaurantController extends Controller
{
//
public function index()
{
$use=User::all();
$res=restaurant::all();
$add=address::all();
return view('NewMember',compact('use','res','add'));
}
public function create()
{
// $restaurant=restaurant::all();
// return view('restaurant.NewMember',compact($restaurant));
return view('NewMember');
}
/**
* #param $id
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function show()
{
// $restaurant1= restaurant::find($id);
// return view('restaurantmenus/',$restaurant1);
return view('restaurantmenus');
}
public function store(Request $request)
{
// taking the restaurant user information
$restaurantUser = new User();
$restaurantUser->email = $request->email;
$restaurantUser->username = $request->username;
$restaurantUser->type = 'restaurant';
$restaurantUser->password = Hash::make($request->password);
$restaurantUser->save();
//taking the restaurant information
$object = new restaurant();
$object->name = $request->name;
$object->telephone = $request->Telephone;
$object->description = $request->description;
$object->delivery = $request->delivery;
$object->DeliveryPrice = $request->DeliveryPrice;
$object->kitchen = $request->kitchen;
$object->open = $request->open;
$object->close = $request->close;
$object->user_id = $restaurantUser->id;
$object->$restaurantUser->save();
// dd($object->IDrestaurant);
// taking the restaurant address
$addr = new address();
$addr->city = $request->city;
$addr->region = $request->region;
$addr->restaurant_id = $object->id;
$addr->$object->$restaurantUser->save();
$idr = $object->IDrestaurant;
return redirect('/restaurantmenus/' . $idr);
}
}
}
the route I think the problem in the post route .csrf_token() is not allowing the post route to send the data to database. I'd tried to add the routes to $except in VerifyCsrfToken class but it did not work
Route::post('/NewMember','restaurantController#store');
Route::get('/NewMember','restaurantController#create');
Route::get('/restaurantmenus','restaurantController#show');
i created one view.blade.php page. There in table added column action, inside that given to button, Delete and View/Edit. When i click on View/Edit button one form page should come as pop up box. For that how can i write javascript. I am a beginner in laravel. So can any one please help me out?
My view.blade page is given is given below
userAdmin.blade.php
#extends('app')
#section('content')
<div class="templatemo-content-wrapper" xmlns="http://www.w3.org/1999/html">
<ol class="breadcrumb">
<li><font color="green">Home</font></li>
<li class="active">user information</li>
</ol>
<div class="templatemo-content">
<h1>View/Edit user information</h1>
<div>
<div>
<div>
<table id="example" class="table table-striped table-hover table-bordered" bgcolor="#fff8dc">
<h3>Select User :</h3>
<thead>
<tr>
<th>User ID</th>
<th>User Desc</th>
<th>Contact Name</th>
<th>Contact Email</th>
<th>Time Zone</th>
<th>Active</th>
<th>Last Login (GMT+05:30)</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{{--{{ UserController::getIndex() }}--}}
#foreach($name as $nam)
<tr>
<td>{{ $nam->userID }}</td>
<td>{{ $nam->description }}</td>
<td>{{ $nam->contactName }}</td>
<td>{{ $nam->contactPhone }}</td>
<td>{{ $nam->timeZone }}</td>
<td>
#if($nam->isActive == '1')
Yes
#else
No
#endif
</td>
<td>{{ date('Y/m/d H:i:s',($nam->lastLoginTime)) }}</td>
<td>
{{--#if ( in_array($nam->isActive, array('Yes','No')) )--}}
<div class="btn-group">
<button type="button" class="btn btn-info">Action</button>
<button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
{{--#if ($nam->isActive == 'Yes')--}}
<li data-toggle="modal" data-target="#acceptModal" data-bookingid="{{ $nam->userID }}">View/ Edit
</li>
{{--#endif--}}
<li>Delete</li>
</ul>
</div>
{{--#endif--}}
</td>
</tr>
#endforeach
</tbody>
</table>
{{$name->links()}}
</div>
</div>
</div>
</div>
</div>
</br>
<script type="text/javascript">
$(document).ready(function() {
$('#example').dataTable();
} );
</script>
#endsection
and the form page i need to pop up is
#extends('app')
#section('content')
<div class="templatemo-content-wrapper">
<div class="container">
<ol class="breadcrumb">
<li><font color="green">Home</font></li>
<li class="active">View/Edit User</li>
</ol>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-success">
<div class="panel-heading">View/Edit User Information</div>
<div class="panel-body">
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form class="form-horizontal" role="form" method="POST" action="{{ url('accountAdmin') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="col-md-4 control-label">User ID</label>
<div class="col-md-6">
<input type="text" class="form-control" name="userID" value="{{ old('userID')}}" placeholder="Enter User ID">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Active</label>
<div class="col-md-6">
<select class="form-control" value="{{ old('isActive') }}" name="isActive" >
<option value="1">Yes</option>
<option value="0">No</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">User Description</label>
<div class="col-md-6">
<input type="text" class="form-control" name="description" value="{{ old('description') }}" placeholder="Enter the description">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Contact Name</label>
<div class="col-md-6">
<input type="text" class="form-control" name="contactName" value="{{ old('contactName') }}" placeholder="Enter Contact Name">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Contact Phone</label>
<div class="col-md-6">
<input type="text" class="form-control" name="contactPhone" value="{{ old('contactPhone') }}" placeholder="Enter Mobile Number">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Contact Email</label>
<div class="col-md-6">
<input type="email" class="form-control" name="contactEmail" value="{{ old('contactEmail') }}" placeholder="Enter E-Mail Address">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Notify Email</label>
<div class="col-md-6">
<input type="email" class="form-control" name="notifyEmail" value="{{ old('notifyEmail') }}" placeholder="Enter E-Mail Address">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Time Zone</label>
<div class="col-md-6">
<select class="form-control" value="{{ old('timeZone') }}" name="timeZone" >
<option value="0">GMT+05:30</option>
<option value="Inactive">xyz</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Authorized Group</label>
<div class="col-md-6">
<select class="form-control" value="{{ old('distanceUnits') }}" name="distanceUnits" >
<option value="0">all</option>
<option value="1">Km</option>
<option value="2">Nm</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">First Login page</label>
<div class="col-md-6">
<select class="form-control" value="{{ old('firstLoginPageID') }}" name="firstLoginPageID" >
<option value="0">Main Menu</option>
<option value="1">Liter</option>
<option value="2">IG</option>
<option value="3">ft^3</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Maximum Access Level</label>
<div class="col-md-6">
<select class="form-control" value="{{ old('maxAccessLevel') }}" name="maxAccessLevel" >
<option value="3">New/Delete</option>
<option value="1">Read/View</option>
<option value="2">Write/Edit</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-warning">
Save
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
userController page is
class UserController extends Controller
{
public $type = 'User';
public function getIndex()
{
$name = DB::table('user')->simplePaginate(10);
return view('user.userAdmin')->with('name', $name);
}
public function getData()
{
$name = DB::table('user');
return view('user.add')->with('name', $name);
}
public function userInsert()
{
$postUser = Input::all();
//insert data into mysql table
$data = array('userID'=> $postUser['userID']
);
// echo print_r($data);
$ck = 0;
$ck = DB::table('user')->Insert($data);
//echo "Record Added Successfully!";
$name = DB::table('user')->simplePaginate(10);
return view('user.userAdmin')->with('name', $name);
}
public function delete($id)
{
DB::table('user')->where('userID', '=', $id)->delete();
return redirect('userAdmin');
}
}
routes.php is
Route::any('userAdmin', 'UserController#getIndex');
Route::any('user/add', 'UserController#getData');
Route::any('user/delete/{id}', 'UserController#delete');
Route::post('userAdmin', 'UserController#userInsert');
Anyone please tell me how to write js code for that
I'm submitting a form through JQuery by using the form.serialize method. But that same form has an array of checkboxes, which is dynamically genetrated by a PHP function
This is the form:
<form class="form" id="formNewClient" role="form">
<ul class="nav nav-tabs">
<li class="active"><i class="fa fa-user"></i> Dados Cliente</li>
<li><i class="fa fa-phone"></i> Dados Phonepark</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="clientdata">
<div class="row">
<div class="col-md-12">
<div class="page-header"><h3>Dados Pessoais</h3></div>
</div>
</div>
<div class="row">
<div class="form-group col-md-8">
<label for="name">Nome Completo:*</label>
<input type="text" name="clientName" class="form-control" placeholder="Nome Completo do Utilizador">
</div>
</div>
<div class="row">
<div class="form-group col-md-8">
<label for="email">Email:</label>
<input type="text" name="clientEmail" class="form-control" placeholder="Email Utilizador">
</div>
</div>
<div class="row">
<div class="form-group col-md-8">
<label for="addressone">Morada:</label>
<input type="text" name="clientAddressone" class="form-control" placeholder="Morada do Utilizador">
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="address2">Morada (cont.):</label>
<input type="text" name="clientAddresstwo" class="form-control" placeholder="Morada do Utilizador (cont.)">
</div>
<div class="form-group col-md-3">
<label for="postalcode">Código Postal:</label>
<input type="text" name="clientCPostal" class="form-control" placeholder="Código Postal">
</div>
<div class="form-group col-md-3">
<label for="city">Localidade:</label>
<input type="text" name="clientCity" class="form-control" placeholder="Localidade">
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="clientNif">NIF</label>
<input type="text" name="clientNif" class="form-control " placeholder="NIF">
</div>
<div class="form-group col-md-4">
<label for="clientBirthdate">Data de Nascimento</label>
<div class="form-group">
<div class='input-group date' id='inputendDate' data-date-format="YYYY/MM/DD">
<input type='text' name="clientBirthdate" class="form-control" />
<span class="input-group-addon"><span class="glyphicon glyphicon-time"></span>
</div>
</div>
</div>
<div class="form-group col-md-4">
<label for="sex">Sexo:</label>
<br>
<label class="radio-inline">
<input type="radio" name="optionsRadioSex" value="M">
Masculino
</label>
<label class="radio-inline">
<input type="radio" name="optionsRadioSex" value="F">
Feminino
</label>
</div>
</div>
</div>
<!--END CLIENTDATA-->
<div class="tab-pane" id="phoneparkdata">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h3>Dados Phonepark</h3>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12"><h4>Documentos:</h4></div>
<div class="form-group col-md-4">
<label for="document">Tipo de Documento:</label>
<select name="documenttype" class="form-control">
<?php selectListDocuments();?>
</select>
</div>
<div class="form-group col-md-4">
<label for="documentNumber">Número do Documento:*</label>
<input type="text" name="documentNumber" class="form-control">
</div>
<div class="form-group col-md-4">
<label for="documentNumber">Número do Documento (Secundário):</label>
<input type="text" name="documentNumberSec" class="form-control">
</div>
</div>
<div class="row">
<div class="col-md-12"><h4>Comunicações:</h4></div>
<div class="form-group col-md-4">
<label for="phone1">Telemóvel:*</label>
<input type="text" name="clientPhonePri" class="form-control">
</div>
<div class="form-group col-md-4">
<label for="phone2">Telemóvel Secundário:</label>
<input type="text" name="clientPhoneSec" class="form-control">
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<h4>Perfil:</h4>
<label for="profile">Perfil(s) a utilizar:*</label>
<?php
profileCheckBoxes();
?>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="activationDate">Data de Activação:</label>
<div class="form-group">
<div class='input-group date' id='inputactivationDate' data-date-format="YYYY/MM/DD hh:mm">
<input type='text' name="clientActivationTime" class="form-control" />
<span class="input-group-addon"><span class="glyphicon glyphicon-time"></span>
</div>
</div>
</div>
<div class="form-group col-md-6">
<label for="limitDate">Data de Limite:</label>
<div class="form-group">
<div class='input-group date' id='inputendDate' data-date-format="YYYY/MM/DD hh:mm">
<input type='text' name="clientDeactivationTime" class="form-control" />
<span class="input-group-addon"><span class="glyphicon glyphicon-time"></span>
</div>
</div>
</div>
</div>
</div>
<!--END PHONEPARKDATA-->
</div>
<!--END TAB-CONTENT-->
<div class="row">
<div class="col-md-4 col-lg-4 pull-right">
<button type="submit" class="btn btn-success" name="submitNewClient" id="submitNewClient"><i class="fa fa-plus"></i> Adicionar Cliente</button>
<button type="button" class="btn btn-danger" data-dismiss="modal"><i class="fa fa-times"></i> Cancelar</button>
</div>
</div>
</form>
And this is the php function that generates the checkboxes:
function profileCheckBoxes(){
$queryListProfiles = "SELECT * FROM perfil";
$listProfiles = mysqli_query($GLOBALS['dbc'],$queryListProfiles);
$numProfiles = mysqli_num_rows($listProfiles);
if($numProfiles !=""){
while($row = mysqli_fetch_array($listProfiles)){
?>
<label class="checkbox-inline">
<input type="checkbox" value="<?php echo $row['id']?>" name="profiles[]">
<?php echo $row['Nome']; ?>
</label>
<?php
}
}
}
How can I submit the form with form.serialize in Jquery and in the PHP side process the checkbox so I can extract the values from the checkbox array?
This jQuery documentation page explains how to use the serialize function:
http://api.jquery.com/serialize/
If you then pass the output to your php page using POST, in the PHP script the checked values will be stored in $_POST['profiles'] as an array. So to loop through the values of the checked boxes you could use:
foreach ($_POST['profiles'] as $profile) {
//process code here
}
jQuery's form.serialize only pass checksboxes that are checked.
if you want all your checkboxes to get passed to your server consider to generate also hidden inputs to store those values.
I would also change the checkboxes name to "profiles"