Show duplicate entry warning in laravel - php

how to display duplicate entry warning error to my view in laravel blade. so when they key in same name the warning will appear when they saved it.
Note: i have already make my Schema $table->string('studentname')->unique();;
Controller
public function store(Request $request)
{
$this->validate($request, [
'studentname'=>'required|max:50',
]);
$students = new Student();
$students->studentname = $request->studentname;
$students->address = $request->address;
$students->religion = $request->religion;
$students->save();
return redirect()->route('students.index')
->with('flash_message', 'Success.');
}
View-Blade
<div class="container">
<h1 class="well">Registration Form</h1>
<div class="col-lg-12 well">
<div class="row">
<form action="{{route('students.store')}}" method="POST">
{{csrf_field()}}
<div class="col-sm-12">
<h3>CHILD'S INFORMATION</h3>
<hr>
<div class="row">
<div class="col-sm-4 form-group">
<label>FULLNAME</label>
<input type="text" name="studentname" value="" placeholder="Enter FULLNAME.." class="form-control" required>
</div>
<div class="col-sm-4 form-group">
<label>RELIGION</label>
<input type="text" name="religion" value="" placeholder="Enter RELIGION.." class="form-control">
</div>
<div class="col-sm-4 form-group">
<label>ADDRESS</label>
<input type="text" name="address" value="" placeholder="Enter ADDRESS.." class="form-control">
</div>
<div>
<button type="submit" class="btn btn-default">SUBMIT</button>
</div>
</div>
</div>
</div>

Add the unique validation which returns a message if it fails.
$this->validate($request, [
'studentname'=>'required|max:50|unique:table_name,studentname',
]);
And then, in your blade template, do this.
<div class="col-sm-4 form-group {{ $errors->get('studentname') ? 'has-error' : '' }}">
<label>FULLNAME</label>
<input type="text" name="studentname" value="" placeholder="Enter FULLNAME.." class="form-control" required>
#foreach($errors->get('studentname') as $error)
<span class="help-block">{{ $error }}</span>
#endforeach
</div>

Related

Can't insert data on my database from laravel

When I try to insert data into my database, Laravel does not insert the records, but it is strange because when I migrate the tables to be able to perform the database, Laravel creates them without any problem, I do not know what I can be doing wrong if the migration run but stored no
Route:
Route::post('/proyecto', [ctrlCars::class,'store'])->name('cars');
Controler:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\cars;
class ctrlCars extends Controller
{
public function store(Request $request){
$request->validate([
'carRegistration'=> ['required','min:6'],
'name'=> ['required','min:6'],
'fromProduction' => ['required','min:6'],
'stateStored'=> ['required'],
'model'=> ['required','min:4'],
'dateAssembled' => ['required'],
]);
$car = new cars;
$car->carRegistration = $request->carRegistration;
$car->name = $request->name;
$car->fromProduction = $request->fromProduction;
$car->stateStored = $request->stateStored;
$car->model = $request->model;
$car->dateAssembled = $request->dateAssembled;
$car-> save();
return redirect()->route('cars')->with('success','Registro guardado satisfactoriamente');
}}
Template:
#extends('header')
#section('content')
<div class="container w-10 mt-5 border p-4">
<form action="{{ route('cars') }}" method="POST">
#csrf
#if (session('success'))
<h6 class="alert alert-success">{{ session('success') }}</h6>
#endif
#error('carRegistration')
<h6 class="alert alert-danger">{{ $message }}</h6>
#enderror
<p class="h2">Registro vehiculos</p>
<br>
<div class="row">
<section class="col-md-12">
<div class="form-group">
<section class="row">
<div class="col-md-4">
<label for="carRegistration" class="form-label">Placa</label>
<input type="text" class="form-control" name="carRegistration" placeholder="CDE001" maxlength="6">
</div>
<div class="col-md-4">
<label for="name" class="form-label">Nombre</label>
<input type="text" class="form-control" name="name" placeholder="Ferrari Enzo">
</div>
<div class="col-md-4">
<label for="fromProduction" class="form-label">Planta Produccion</label>
<input type="text" class="form-control" name="fromProduction" placeholder="Bmw sede1">
</div>
</section>
<section class="row mt-4">
<div class="col-md-4">
<label for="placa" class="form-label">Fecha Ensamble</label>
<input type="date" class="form-control" name="dateAssembled" placeholder="CDE001">
</div>
<div class="col-md-4">
<label for="model" class="form-label">Módelo Matricula</label>
<input type="text" class="form-control" name="model" maxlength="4" placeholder="2013">
</div>
<div class="col-md-4">
<label for="stateStored" class="form-label">Ciudad Almacenamiento</label>
<Select type="text" class="form-control" id="stateStored" placeholder="Medellin">
<option value=''>Elija una opción</option>
<option value='Medellin'>Medellín</option>
<option value="Bucaramanga">Bucaramanga</option>
<option value="Cali">Cali</option>
<option value="Bogota">Bogotá</option>
</Select>
</div>
</section>
</div>
</section>
</div>
<button type="submit" class="btn btn-success mt-4">Guardar</button>
</form>
</div>
The problem is from your template. The select tag should have a name attribute.
Change your template to this
$car->dateAssembled = $request->dateAssembled;
$car-> save();
return redirect()->route('cars')->with('success','Registro guardado satisfactoriamente');
}}
Template:
#extends('header')
#section('content')
<div class="container w-10 mt-5 border p-4">
<form action="{{ route('cars') }}" method="POST">
#csrf
#if (session('success'))
<h6 class="alert alert-success">{{ session('success') }}</h6>
#endif
#error('carRegistration')
<h6 class="alert alert-danger">{{ $message }}</h6>
#enderror
<p class="h2">Registro vehiculos</p>
<br>
<div class="row">
<section class="col-md-12">
<div class="form-group">
<section class="row">
<div class="col-md-4">
<label for="carRegistration" class="form-label">Placa</label>
<input type="text" class="form-control" name="carRegistration" placeholder="CDE001" maxlength="6">
</div>
<div class="col-md-4">
<label for="name" class="form-label">Nombre</label>
<input type="text" class="form-control" name="name" placeholder="Ferrari Enzo">
</div>
<div class="col-md-4">
<label for="fromProduction" class="form-label">Planta Produccion</label>
<input type="text" class="form-control" name="fromProduction" placeholder="Bmw sede1">
</div>
</section>
<section class="row mt-4">
<div class="col-md-4">
<label for="placa" class="form-label">Fecha Ensamble</label>
<input type="date" class="form-control" name="dateAssembled" placeholder="CDE001">
</div>
<div class="col-md-4">
<label for="model" class="form-label">Módelo Matricula</label>
<input type="text" class="form-control" name="model" maxlength="4" placeholder="2013">
</div>
<div class="col-md-4">
<label for="stateStored" class="form-label">Ciudad Almacenamiento</label>
<Select type="text" name="stateStored" class="form-control" id="stateStored" placeholder="Medellin">
<option value=''>Elija una opción</option>
<option value='Medellin'>Medellín</option>
<option value="Bucaramanga">Bucaramanga</option>
<option value="Cali">Cali</option>
<option value="Bogota">Bogotá</option>
</Select>
</div>
</section>
</div>
</section>
</div>
<button type="submit" class="btn btn-success mt-4">Guardar</button>
</form>
</div>
Thanks for help, the error come from because I call from name on the controller and in this input only have ID, and in the validation for this field have 'required';
I don't know how reply comments, but thanks aynber and Daniel L, you were nice help
First time Comment your validation section and try again. If your data successfully inserted. Then Your need to modify your required field like below.
Replace
['required','min:6']
Like this:
'required|min:6',

302 found in Laravel project

Route
Route::get('/addproduct', [UserController::class, 'addproduct'])->name('addproduct');
Route::post('/addnewproduct', [UserController::class, 'addnewproduct'])->name('addnewproduct');
Route::get('/showproducts', [UserController::class, 'showproducts'])->name('showproducts');
Controller
public function addproduct()
{
return view('addProduct');
}
public function addnewproduct(Request $request)
{
$user_id = Auth::user()->id;
$request->validate([
'file' => 'required|mimes:jpg,png,gif,svg',
'name' => 'required|string|min:3|max:30',
'description' => 'required|string|min:1|max:255',
'category' => 'required|string|max:255',
]);
$productModel = new Product();
$filename =time().'_' .$request->name;
$filePath = $request->file('file')->move('upload', $filename);
$productModel->name = $request->name;
$productModel->description = $request->description;
$productModel->category = $request->category;
$productModel->image = $filePath;
$productModel->save();
return redirect()->route('showproducts');
}
public function showproducts()
{
$user_id = Auth::user()->id;
$results=DB::select('SELECT * FROM products');
$data = [
'results' =>$results
];
return view('showProduct')->with($data);
}
View
<div class="card-body">
<form method="POST" action="{{ route('addnewproduct') }}" class="needs-validation form" enctype="multipart/form-data" novalidate>
#csrf
<div class="row">
<div class="col-sm-6">
<input type="file" id="input-file-now" class="form-control dropify" name="file" required/>
</div>
<div class="col-sm-6">
<div class="row mb-3">
<label for="validationName" class="form-label">Product name</label>
<div class="input-group has-validation">
<input type="text" class="form-control" name="name" id="validationName" aria-describedby="inputGroupPrepend" required>
<div class="invalid-feedback">
You have to enter Product name!
</div>
</div>
</div>
<div class="row mb-3">
<label for="validationCategory" class="form-label">Category</label>
<div class="input-group has-validation">
<select class="form-select" name="category" id="validationCategory" required>
<option selected disabled value="">Select...</option>
<option value="c1">c1</option>
<option value="c2">c2</option>
</select>
</div>
<div class="invalid-feedback">
Please select Category
</div>
</div>
<div class="row mb-3">
<label for="validationDes" class="form-label">Description</label>
<div class="input-group has-validation">
<textarea type="text" class="form-control text-des" name="address" id="validationDes" aria-describedby="inputGroupPrepend" required></textarea>
<div class="invalid-feedback">
Please enter product descriiption in here.
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
<label class="form-check-label" for="invalidCheck">
Check it.
</label>
<div class="invalid-feedback">
You have to checkbox!
</div>
</div>
</div>
<div class="row">
<div class="float-end">
<button class="btn btn-primary sumbtn float-end" type="submit"><i class="bi bi-person-plus-fill"></i> ADD</button>
</div>
</div>
</form>
</div>
after enter all fields and file select and then click checkbox, but when I click button don't go to showproducts page, and don't save enterd data and file.
view screenshot
after click button get 302 and not redirect to "showproducts"
Please help me, I'm very very stress with that problem

the store() controller is not working in laravel 5.7

i am working on crating a post for my blog app. laravel 5.7 . but when i want to create a new post it dose not redarect to the index page of the post ...it is just refresh the crate page .......i don't know why its not working .......here is my create blade page
#extends('layouts.app')
#section('content')
<div class="card card-defualt">
<div class="card-header"> Create post</div>
<div class="card-body">
<form action="{{route('posts.store')}}" method="POST" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="Title" class="form-control">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" id="description" cols="5" rows="5" class="form-control"></textarea>
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea name="content" id="content" cols="5" rows="5" class="form-control"></textarea>
</div>
<div class="form-group">
<label for="published_at">Published At</label>
<input type="text" name="published_at" class="form-control">
</div>
<div class="form-group">
<label for="image">Image</label>
<input type="file" name="image" id="image" class="form-control">
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Create post</button>
</div>
</form>
</div>
#endsection
and post controller
public function store(createpostrequest $request)
{
$image=$request->image->store('posts');
post::create([
'title'=>$request->title,
'description'=>$request->description,
'content'=>$request->content,
'image'=>$image
]);
//flashing the message
session()->flash('success','catagory created successfully');
return redirect(route('posts.index'));
}
and here is the request
{
return [
//
'title'=>'required|unique:posts',
'description'=>'required',
'content'=>'required',
'image'=>'required|image'
];
}

NotFoundHttpException in RouteCollection.php line 161: laravel 5.2

I created one table in one page, to that table fetching data from database. Then give dynamic buttons for delete and Edit/View. When i click on Delete , it will delete corresponding row from database. Previously it was working properly. But now it showing error "NotFoundHttpException in RouteCollection.php line 161:". Can anyone tell what wrong i did in my code?
My vehicleController.php
<?php
namespace App\Http\Controllers;
use Mail;
use Illuminate\Support\Facades\DB;
use App\Device;
use App\Account;
use App\Http\Requests\createUserRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Illuminate\Pagination\Paginator;
class VehicleController extends Controller
{
public $type = 'Device';
public function getIndex()
{
$devices = DB::table('device')->simplePaginate(15);
return view('vehicle.vehicleAdmin')->with('devices', $devices);
}
public function vehicleInsert()
{
$postUser = Input::all();
//insert data into mysql table
$account = Account::select('accountID')->get();
foreach ($account as $acc) {
$abc = $acc->accountID;
}
$data = array("accountID" => $abc,
"vehicleID"=> $postUser['vehicleID']
);
// echo print_r($data);
$ck = 0;
$ck = DB::table('device')->Insert($data);
//echo "Record Added Successfully!";
$devices = DB::table('device')->simplePaginate(50);
return view('vehicle.vehicleAdmin')->with('devices', $devices);
}
public function delete($id)
{
DB::table('device')->where('vehicleID', '=', $id)->delete();
return redirect('vehicleAdmin');
}
public function edit($id)
{
try {
//Find the user object from model if it exists
$devices = DB::table('device')->where('vehicleID', '=', $id)->get();
//$user = User::findOrFail($id);
//Redirect to edit user form with the user info found above.
return view('vehicle.add')->with('devices', $devices);
} catch (ModelNotFoundException $err) {
//redirect to your error page
}
}
}
my vehicleAdmin.blade,php
#extends('app')
#section('content')
<div class="templatemo-content-wrapper">
<div class="templatemo-content">
<ol class="breadcrumb">
<li><font color="green">Home</font></li>
<li class="active">Vehicle information</li>
</ol>
<h1>View/Edit Vehicle information</h1>
<p></p>
<div class="row">
<div class="col-md-12">
<div class="table-responsive" style="overflow-x:auto;">
<table id="example" class="table table-striped table-hover table-bordered" bgcolor="#fff8dc">
<h3>Select a Vehicle :</h3>
<thead>
<tr>
<th>Vehicle ID</th>
<th>Unique ID</th>
<th>Description</th>
<th>Equipment Type</th>
<th>SIM Phone</th>
<th>Server ID</th>
<th>Ignition State</th>
<th>Expecting ACK</th>
<th>Active</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
#foreach($devices as $device)
<tr>
<td>{{ $device->vehicleID }}</td>
<td>{{ $device->uniqueID }}</td>
<td>{{ $device->description }}</td>
<td>{{ $device->equipmentType }}</td>
<td>{{ $device->simPhoneNumber }}</td>
<td></td>
<td>
#if(#$device->ignitionIndex == '0')
OFF
#else
ON
#endif
</td>
<td>{{ $device->expectAck }}</td>
<td>
#if($device->isActive == '1')
Yes
#else
No
#endif
</td>
<td>
<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">
<li>
View/ Edit
</li>
<li>Delete</li>
</ul>
</div>
</td>
</tr>
#endforeach
</tbody>
</table>
{{--{!! $results->appends(['sort' => $sort])->render() !!}--}}
{{$devices->links()}}
</div>
</div>
</div>
</div>
</div>
{{--{!! $device->links()!!}--}}
</br>
<h4>Create a new Vehicle</h4>
<form role="form" method="POST" action="{{ url('vehicleAdmin') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="row">
<div class="col-md-6 margin-bottom-15">
<input type="text" class="form-control" name="vehicleID" value="{{ old('vehicleID') }}" placeholder="Enter vehicle ID">
</div>
<div class="row templatemo-form-buttons">
<div class="submit-button">
<button type="submit" class="btn btn-primary">New</button>
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#example').dataTable();
} );
</script>
#endsection
Edit page add.blade.php
#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 Vehicle</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 Vehicle 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('vehicle/update/') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
#foreach($devices as $device)
<div class="form-group">
<label class="col-md-4 control-label">Vehicle ID</label>
<div class="col-md-6">
<input type="text" class="form-control" name="vehicleID" value="{{ ($device->vehicleID)}}" placeholder="Enter User ID">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Creation date</label>
<div class="col-md-6">
<input type="text" class="form-control" name="creationTime" value="{{ ($device->creationTime)}}">
</div>
</div>
<!--<div class="form-group">
<label class="col-md-4 control-label">Server ID</label>
<div class="col-md-6">
<input type="text" class="form-control" name="userID" value="{{ ($device->userID)}}" placeholder="Enter User ID">
</div>
</div> -->
<div class="form-group">
<label class="col-md-4 control-label">Unique ID</label>
<div class="col-md-6">
<input type="text" class="form-control" name="uniqueID" value="{{ ($device->uniqueID)}}" placeholder="Enter Unique 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="{{ ($device->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">Vehicle Description</label>
<div class="col-md-6">
<input type="text" class="form-control" name="description" value="{{ ($device->description) }}" placeholder="Enter the description">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Short Name</label>
<div class="col-md-6">
<input type="text" class="form-control" name="displayName" value="{{ ($device->displayName) }}" placeholder="Enter Contact Name">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Vehicle ID</label>
<div class="col-md-6">
<input type="text" class="form-control" name="vehicleID" value="{{ ($device->vehicleID) }}" placeholder="Enter Vehicle ID">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">License Plate</label>
<div class="col-md-6">
<input type="text" class="form-control" name="licensePlate" value="{{ ($device->licensePlate) }}" placeholder="Enter license Plate">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">License Expiration</label>
<div class="col-md-6">
<input type="text" class="form-control" name="licenseExpire" value="{{ ($device->licenseExpire) }}" placeholder="Enter license Expire Date">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Equipment Type</label>
<div class="col-md-6">
<input type="email" class="form-control" name="equipmentType" value="{{ ($device->equipmentType) }}" placeholder="Enter E-Mail Address">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Equipment Status</label>
<div class="col-md-6">
<select class="form-control" value="{{ ($device->equipmentStatus) }}" name="equipmentStatus" >
<option value="0">In Service</option>
<option value="#">Rented</option>
<option value="#">Pending</option>
<option value="#">Completed</option>
<option value="#">Available</option>
<option value="#">Unavailable</option>
<option value="#">Repair</option>
<option value="#">Retired</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">IMEI/EDN Number</label>
<div class="col-md-6">
<input type="email" class="form-control" name="notifyEmail" value="{{ ($device->imeiNumber) }}" placeholder="Enter IMEI/EDN Number">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Serial Number</label>
<div class="col-md-6">
<input type="email" class="form-control" name="notifyEmail" value="{{ ($device->serialNumber) }}" placeholder="Enter Serial Number">
</div>
</div>
<!-- <div class="form-group">
<label class="col-md-4 control-label">Data Key</label>
<div class="col-md-6">
<input type="email" class="form-control" name="notifyEmail" value="{{ ($device->notifyEmail) }}" placeholder="Enter E-Mail Address">
</div>
</div> -->
<div class="form-group">
<label class="col-md-4 control-label">SIM Phone</label>
<div class="col-md-6">
<input type="email" class="form-control" name="notifyEmail" value="{{ ($device->simPhoneNumber) }}" placeholder="Enter SIM Phone Number">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">SMS Email Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="notifyEmail" value="{{ ($device->smsEmail) }}" placeholder="Enter SMS E-Mail Address">
</div>
</div>
<!-- <div class="form-group">
<label class="col-md-4 control-label">Group Pushpin ID</label>
<div class="col-md-6">
<input type="email" class="form-control" name="notifyEmail" value="{{ ($device->notifyEmail) }}" placeholder="Enter E-Mail Address">
</div>
</div> -->
<div class="form-group">
<label class="col-md-4 control-label">Map Route Color</label>
<div class="col-md-6">
<select class="form-control" value="{{ ($device->timeZone) }}" name="timeZone" >
<option value="0">Black</option>
<option value="#">Brown</option>
<option value="#">Red</option>
<option value="#">Orange</option>
<option value="#">Green</option>
<option value="#">Blue</option>
<option value="#">Purple</option>
<option value="#">Grey</option>
<option value="#">Cyan</option>
<option value="#">Pink</option>
<option value="#">None</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Fuel Capacity</label>
<div class="col-md-6">
<input type="email" class="form-control" name="fuelCapacity" value="{{ ($device->fuelCapacity) }}" >
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Driver ID</label>
<div class="col-md-6">
<input type="email" class="form-control" name="driverID" value="{{ ($device->driverID) }}">
</div>
</div>
<!-- <div class="form-group">
<label class="col-md-4 control-label">Reported Odometer</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">Reported Engine Hours</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">
<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
Routes.php
Route::any('vehicleAdmin', 'VehicleController#getIndex');
Route::post('vehicleAdmin', 'VehicleController#vehicleInsert');
Route::get('vehicle/edit/{id}', 'VehicleController#edit');
Route::delete('vehicle/delete/{id}', 'VehicleController#delete');
I think when you click the link, it is probably sending a GET request to that end point unless you set the method to delete in ajax call,. CRUD in Laravel works according to REST. This means it is expecting a DELETE request instead of GET.
So I would suggest you to make your route as follow
Route::get('/vehicle/delete/{id}', 'VehicleController#delete');

Populate ng-model - Value not working AngularJS

I have an AngularJS front end for a new internal web portal I am building. Using value={{data.Param}} I have successfully gotten my get and create requests to work via Slim PHP. Now however I am trying to create a PUT request and I am running into an issue.
This is the current code for my "Update /PUT" page.
request-edit.html
<div class="jumbotron text-center">
<form class="form-horizontal" role="form">
<div class="form-group">
<div class="text-center">
<h1>{{ header }}</h1>
<br/>
<h3>{{ request.Header }}</h3>
<br/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Id:</label>
<div class="col-sm-3">
<input name="id" class="form-control" type="text" value="{{request.ID}}" disabled />
</div>
<label class="col-sm-3 control-label">Date:</label>
<div class="col-sm-3">
<input type="text" class="form-control" value="{{ request.Date_Submitted }}" disabled/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Change Initiator:</label>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="{{request.Change_Initiator}}" ng-model="request.changeInitiator"/>
</div>
<label class="col-sm-3 control-label">Risk Level:</label>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="{{ request.Risk_Level }}" ng-model="request.riskLevel" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">CI Details:</label>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="{{ request.Change_Initiator_id }}" ng-model="request.changeInitiatorId" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Requestor:</label>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="{{ request.Requestor }}" ng-model="request.requestor" />
</div>
<label class="col-sm-3 control-label">Systems Affected:</label>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="{{ request.Systems_Affected }}" ng-model="request.systemsAffected" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Implemented By:</label>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="{{ request.Implemented_By }}" ng-model="request.implementationBy" />
</div>
<label class="col-sm-3 control-label">Implementation Date:</label>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="{{ request.Implementation_Date }}" ng-model="request.implementationDate" bs-datepicker/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Close Date:</label>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="{{ request.Close_Date }}" ng-model="request.closeDate" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Work to be Performed:</label>
<div class="col-sm-3">
<textarea name="request.description" ng-model="request.workToBePerformed" placeholder="{{ request.Work_to_be_performed }}" ></textarea>
</div>
<label class="col-sm-3 control-label">Backout Plan:</label>
<div class="col-sm-3">
<textarea name="request.description" ng-model="request.backoutPlan" placeholder="{{ request.Backout_Plan }}" ></textarea>
</div>
</div>
<div class="form-group">
<button class="update" ng:click="updateRequest()">Save Edits</button>
<button class="approve" ng:click="approveRequest()">Approve</button>
</div>
</form>
<div class="form-group">
<a href="#/requests" class="btn btn-default pull-right">
<span class="glyphicon glyphicon-arrow-left"></span> Back
</a>
</div>
</div>
My confusion in with ng-model, value and placeholders. Currently all my data populates in the form, but when the user goes to update the page they have to re-fill out every box or else blank data will be pushed. I understand the Placeholder does not actually fill in the data - however I have been un-able to use both ng-model and value on the same input field.
My top two fields populate using value just fine, but I do not want people to edit the date or ID. My other fields show the correct data in a temp form using placeholder but do not populate using ng-model. Additionally when my user goes to make the update the ng-model DOES function.
So in short my current issue is that ng-model does not display the original data- but does push it correctly. This causes my users to have to re-type all the data everytime or else the record will be updated with null values.
Below is the rest of my logic for review.
app.js
var app = angular.module('changeControlApp', [
'ngRoute',
'ngResource'
]);
//This configures the routes and associates each route with a view and a controller
app.config(function($routeProvider, $locationProvider) {
//$locationProvider.html5Mode(true);
$routeProvider
.when('/', {templateUrl: 'app/partials/request-list.html', controller: 'viewController' })
.when('/requests', {templateUrl: 'app/partials/request-list.html', controller: 'viewController' })
.when('/requests/create', {templateUrl: 'app/partials/request-create.html', controller: 'createRequestController' })
.when('/settings', {templateUrl: 'app/partials/settings.html', controller: 'settingsController'})
.when('/requests/:id', {templateUrl: 'app/partials/request-view.html', controller: 'viewRequestController' })
.when('/requests/edit/:id', {templateUrl: 'app/partials/request-edit.html', controller: 'editRequestController' })
.otherwise({ redirectTo: '/' });
});
app.controller('editRequestController', function($scope, $location, $route, $routeParams, $resource) {
$scope.header = 'Edit Change Request';
// Update User details
var request_Id = $routeParams.id;
if (request_Id) {
var Request = $resource(('http://pdgrosit02v/changeRequest/app/api/requests/'+ request_Id));
$scope.request = Request.get();
}
$scope.updateRequest = function() {
var RequestPut = $resource(('http://pdgrosit02v/changeRequest/app/api/requests/'+ request_Id), {}, { update: { method: 'PUT'}} );
RequestPut.update($scope.request, function() {
// success
$location.path('/requests');
}, function() {
// error
console.log(error);
});
}
});
And the Slim file
index.php
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
use Slim\Slim;
$app = new Slim();
//$paramValue = $app->request->params('paramName');
$app->get('/requests', 'getRequests');
$app->get('/requests/:id', 'getRequest');
$app->post('/requests/create', 'addRequest');
$app->put('/requests/:id', 'updateRequest');
$app->run();
function updateRequest($id) {
$request = Slim::getInstance()->request()->getBody();
$data = json_decode($request, true);
$sql = "UPDATE change_request SET Change_Initiator=:changeInitiator, Change_Initiator_id=:changeInitiatorId, Risk_Level=:riskLevel, Requestor=:requestor, Work_to_be_performed=:workToBePerformed, Backout_Plan=:backoutPlan, Backout_Time=:backoutTime, Implementation_Date=:implementationDate, Header=:title, Systems_Affected=:systemsAffected, Implemented_By=:implementationBy WHERE ID=$id";
//$sql = "UPDATE change_request SET Change_Initiator=:changeInitiator WHERE ID=$id";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindValue(":changeInitiator", $data['changeInitiator']);
$stmt->bindParam(":changeInitiatorId", $data['changeInitiatorId']);
$stmt->bindParam(":riskLevel", $data['riskLevel']);
$stmt->bindParam(":requestor", $data['requestor']);
$stmt->bindParam(":workToBePerformed", $data['workToBePerformed']);
$stmt->bindParam(":backoutPlan", $data['backoutPlan']);
$stmt->bindParam(":backoutTime", $data['backoutTime']);
$stmt->bindParam(":implementationDate", $data['implementationDate']);
$stmt->bindParam(":title", $data['title']);
$stmt->bindParam(":systemsAffected", $data['systemsAffected']);
$stmt->bindParam(":implementationBy", $data['implementationBy']);
$stmt->execute();
$db = null;
echo json_encode($data);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
I figured out the issue, turns out Value and ng-model conflict and I had to modify my form to get the data correctly.
I removed all value commands and replaced them with ng-model="data.keyvalue". I was confused before as I thought you needed to use {{}} when referencing things off the scope.
I also added form validation for updating - new code below
request-edit.html
<div class="jumbotron text-center">
<form class="form-horizontal" role="form" name="requestEditForm" ng-submit="updateRequest()">
<div class="form-group">
<div class="text-center">
<h1>{{ header }}</h1>
<br/>
<h3>Title of request:</h3>
<input name="title" id="title" class="form-control" type="text" ng-model="request.Header" />
<br/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Id:</label>
<div class="col-sm-3">
<input name="id" class="form-control" type="text" value="{{request.ID}}" disabled />
</div>
<label class="col-sm-3 control-label">Date Submitted:</label>
<div class="col-sm-3">
<input type="text" class="form-control" value="{{ request.Date_Submitted }}" disabled/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Change Initiator:</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="request.Change_Initiator" name="changeInitiator" id="changeInitiator" />
<span class="error" ng-show="requestEditForm.changeInitiator.$error.required && requestEditForm.changeInitiator.$dirty">Title is required</span>
</div>
<label class="col-sm-3 control-label">Risk Level:</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="request.Risk_Level" name="riskLevel" id="riskLevel" required/>
<span class="error" ng-show="requestEditForm.riskLevel.$error.required && requestEditForm.riskLevel.$dirty">Risk Level is required</span>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">CI Details:</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="request.Change_Initiator_id" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Requestor:</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="request.Requestor" />
</div>
<label class="col-sm-3 control-label">Systems Affected:</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="request.Systems_Affected" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Implemented By:</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="request.Implemented_By" />
</div>
<label class="col-sm-3 control-label">Implementation Date:</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="request.Implementation_Date" bs-datepicker/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Close Date:</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="request.Close_Date" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Work to be Performed:</label>
<div class="col-sm-3">
<textarea name="request.description" ng-model="request.Work_to_be_performed"></textarea>
</div>
<label class="col-sm-3 control-label">Backout Plan:</label>
<div class="col-sm-3">
<textarea name="request.description" ng-model="request.Backout_Plan"></textarea>
</div>
</div>
<div class="form-group">
<button class="submit">Save Edits</button>
<button class="approve" ng:click="approveRequest()">Approve</button>
</div>
</form>
<div class="form-group">
<a href="#/requests" class="btn btn-default pull-right">
<span class="glyphicon glyphicon-arrow-left"></span> Back
</a>
</div>
</div>

Categories