How to update a database table in laravel 5.2 - php

i created one project in laravel 5.2. In that "myform.blade.php" page , created form for register the user. after registration it will show the current user in table format("index.blade.php"). There i given two dynamic button like the drop inside the table. One for Edit and other for Edit/View. When i click on delete button it will delete the corresponding row from the database by taken Primary key(employeeID) as reference id, it's working properly. if i click on Edit/View button it will redirect to "edit.blade.php". There i created same form as in myform.blade.php. If we want to edit the details we can edit from there. I can able to fetch the data from database to the form that i created in the "edit.blade.php". But i don't know how to update the data from their without inserting the same data again(It is not possible, because it will create Integrity constraint violation by trying to insert duplicate primary key. Can any one please tell me how to do updation. Replies are appreciable.
"myform.blade.php" 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">Employee Form</li>
</ol>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-success">
<div class="panel-heading">Employee Form</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('myform/myform/') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="col-md-4 control-label">Employee ID</label>
<div class="col-md-6">
<input type="text" class="form-control" name="employeeID" value="{{ old('employeeID') }}" placeholder="Enter employee ID">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">E_number</label>
<div class="col-md-6">
<input type="text" class="form-control" name="employeeNo" value="{{ old('employeeNo') }}" placeholder="Enter employee number">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Name</label>
<div class="col-md-6">
<input type="text" class="form-control" name="Cname" value="{{ old('Cname') }}" placeholder="Enter Contact Name">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">DOB</label>
<div class="col-md-6">
<input type="date" class="form-control" name="dob" value="{{ old('dob') }}" placeholder="Enter date of birth">
</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="phoneNumber" value="{{ old('phoneNumber') }}" placeholder="Enter Mobile Number">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Address</label>
<div class="col-md-6">
<input type="text" class="form-control" name="address" value="{{ old('address') }}" placeholder="Enter 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>
view Data
</form>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
"index.blade.php" is
#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">
<thead>
<tr>
<th>Employee ID</th>
<th>Employee No</th>
<th>Contact Name</th>
<th>Date of birth</th>
<th>Mobile number</th>
<th>address</th>
</tr>
</thead>
<tbody>
{{--{{ UserController::getIndex() }}--}}
#foreach($employer as $emp)
<tr>
<td>{{ $emp->employeeID }}</td>
<td>{{ $emp->employeeNo }}</td>
<td>{{ $emp->Cname }}</td>
<td>{{ $emp->dob }}</td>
<td>{{ $emp->phoneNumber }}</td>
<td>{{ $emp->address }}</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="{{ $emp->employeeID }}">View/ Edit
</li>
{{--#endif--}}
<li>Delete</li>
</ul>
</div>
{{--#endif--}}
</td>
</tr>
#endforeach
</tbody>
</table>
{{$employer->links()}}
</div>
</div>
</div>
</div>
</div>
{{-- <input type="submit" id="add" name="add" value="Edit" class="button">--}}
</br>
<h4>Create a new Employee</h4>
{{--<form class="templatemo-preferences-form" role="form" method="POST" action="{{ action('UserController#save') }}">--}}
{{--<input type="hidden" name="_token" value="{{ csrf_token() }}">--}}
<form role="form" method="POST" action="{{ url('myform/index') }}">
<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="employeeID" value="{{ old('employeeID') }}" placeholder="Enter employee 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>
{{--</form>--}}
<script type="text/javascript">
$(document).ready(function() {
$('#example').dataTable();
} );
</script>
#endsection
"edit.blade.php" 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">Employee Form</li>
</ol>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-success">
<div class="panel-heading">Employee Form</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('myform/myform/') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
#foreach($user as $use)
<div class="form-group">
<label class="col-md-4 control-label">Employee ID</label>
<div class="col-md-6">
<input type="text" class="form-control" name="employeeID" value="{{ $use->employeeID }}" placeholder="Enter employee ID">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">E_number</label>
<div class="col-md-6">
<input type="text" class="form-control" name="employeeNo" value="{{ $use->employeeNo}}" placeholder="Enter employee number">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Name</label>
<div class="col-md-6">
<input type="text" class="form-control" name="Cname" value="{{ $use->Cname }}" placeholder="Enter Contact Name">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">DOB</label>
<div class="col-md-6">
<input type="date" class="form-control" name="dob" value="{{ $use->dob }}" placeholder="Enter date of birth">
</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="phoneNumber" value="{{ $use->phoneNumber }}" placeholder="Enter Mobile Number">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Address</label>
<div class="col-md-6">
<input type="text" class="form-control" name="address" value="{{ $use->address }}" placeholder="Enter Address">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-warning"><a href="{{ url('myform/update/'.$use->employeeID) }}">
Update</a>
</button>
</div>
</div>
{{-- <input type="button" id="add" name="add" value="View data" class="button">--}}
#endforeach
</form>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
"myformController.php" is
<?php
namespace App\Http\Controllers;
use App\myform;
use Mail;
use Illuminate\Support\Facades\DB;
use Faker\Provider\DateTime;
use App\User;
use App\Http\Requests\createUserRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Symfony\Component\HttpFoundation\Request;
class myformController extends Controller
{
public $type = 'myform';
public function getIndex()
{
// $user = DB::table('user')->get();
$employer = DB::table('employee')->simplePaginate(5);
return view('myform.index')->with('employer',$employer);
}
public function formInsert()
{
$postform = Input::all();
//insert data into mysql table
$data = array('employeeID'=> $postform['employeeID'],
'employeeNo'=> $postform['employeeNo'],
'Cname'=> $postform['Cname'],
'dob'=> $postform['dob'],
'phoneNumber'=> $postform['phoneNumber'],
'address'=> $postform['address'],
);
// echo print_r($data);
$ck = 0;
$ck = DB::table('employee')->Insert($data);
//echo "Record Added Successfully!";
$employer = DB::table('employee')->simplePaginate(10);
return view('myform.index')->with('employer',$employer);
}
public function delete($id)
{
DB::table('employee')->where('employeeID', '=', $id)->delete();
$employer = DB::table('employee')->simplePaginate(10);
return view('myform.index')->with('employer', $employer);
}
public function formIDinsert()
{
$postform = Input::all();
//insert data into mysql table
$data = array('employeeID'=> $postform['employeeID'],
);
// echo print_r($data);
$ck = 0;
$ck = DB::table('employee')->Insert($data);
//echo "Record Added Successfully!";
$employer = DB::table('employee')->simplePaginate(10);
return view('myform.index')->with('employer',$employer);
}
public function edit($id)
{
try {
//Find the user object from model if it exists
$user=DB::table('employee')->where('employeeID', '=', $id)->get();
//$user = User::findOrFail($id);
//Redirect to edit user form with the user info found above.
return view('myform.edit')->with ('user', $user);
//return view('myform.edit')->with('user', myform::find($id));
} catch (ModelNotFoundException $err) {
//redirect to your error page
}
}
// Update user
public function update(Request $request, $id)
{
try{
//Find the user object from model if it exists
$user= myform::findOrFail($id);
DB::table('employee')
->where('employeeID', $id)
->update(['employeeNo' =>$request['employeeNo'],
'Cname'=>$request['Cname'],
'phoneNumber'=>$request['phoneNumber'],
'address'=>$request['address']
]);
//Set user object attributes
//the $request index should match your form field ids!!!!!
//you can exclude any field you want.
// $user->employeeNo = $request['employeeNo'];
// $user->Cname = $request['Cname'];
// $user->phoneNumber = $request['phoneNumber'];
// $user->address = $request['address'];
//Save/update user.
$user->save();
return view('myform.index')->with('user', $user);
//redirect to somewhere
}
catch(ModelNotFoundException $err){
//Show error page
}
}
}
model "myform.php" is
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class myform extends Model
{
protected $table = 'employee';
//protected $primaryKey = 'employeeID';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'employeeID',
'employeeNo',
'Cname',
'dob',
'phoneNumber',
'address',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Routes.php is
Route::any('myform', function()
{
return view('myform/myform');
});
Route::any('myform/myform', 'myformController#formInsert');
Route::any('myform/index', 'myformController#getIndex');
//to show edit form and fetch passed user id info from db
Route::get('myform/edit/{id}', 'myformController#edit');
//to get the edited info and save it to db
Route::get('myform/update/{id}', 'UserController#update');
Route::any('myform/index', 'myformController#formIDinsert');
Route::any('myform/delete/{id}', 'myformController#delete');

You wanna change this in your route:
Route::get('myform/update/{id}', 'UserController#update');
to
//Because the data in your form is transferred/submitted by post request
Route::post('myform/update/{id}', 'UserController#update');
then change your update function to this
// Update user
public function update(Request $request, $id)
{
try{
//Find the user object from model if it exists
$user= myform::findOrFail($id);
//$request contain your post data sent from your edit from
//$user is an object which contains the column names of your table
//Set user object attributes
$user->employeeNo = $request['employeeNo'];
$user->Cname = $request['Cname'];
$user->dob = $request['dob'];
$user->phoneNumber = $request['phoneNumber'];
$user->address = $request['address'];
// Save/update user.
// This will will update your the row in ur db.
$user->save();
return view('myform.index')->with('user', $user);
}
catch(ModelNotFoundException $err){
//Show error page
}
}
If you have any question or need clarification you are most welcome to ask :)
Update in your edit view
change this
<form class="form-horizontal" role="form" method="POST" action="{{ url('myform/myform/') }}">
to
<form class="form-horizontal" role="form" method="POST" action="{{ url('myform/update/').$user->employeeID}}">
change $user->employeeID to whatever is your primary key.
Also change this
<button type="submit" class="btn btn-warning"><a href="{{ url('myform/update/'.$use->employeeID) }}">
Update</a>
</button>
to this
<button type="submit" class="btn btn-warning">Update</button>
Aso you didn't fix your route as I mentioned earlier in this answer.

Related

Laravel 7 - Update user

I'm having problems with the 'edit' action of my users. I can create new users, but I cannot update them.
This is my edit method in the UserController:
/**
* Show the form for editing the specified resource.
*
* #param \App\User $user
* #return \Illuminate\Http\Response
*/
public function edit($userID)
{
//
$user = User::query()->findOrFail($userID);
$roles = Role::pluck('nombre_rol','id');
$departments = Department::all(['id','department_name']);
return view('user.edit',compact('user','roles','departments'));
}
This is the update method in the UserController:
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\User $user
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $usuarioID)
{
$user = User::query()->findOrFail($usuarioID);
$user->update($request->only('name','email','password', 'roles', 'departament_id'));
$user->roles()->sync($request->roles);
return back()->with('Success','Usuario actualizado con éxito');
}
This is the view for the edit:
<body id="bodyForm">
<div class="container">
<h2 class="text-center txt-unam-gold">#lang('edit.Editar') #lang('edit.Usuario')</i></h1>
<h4 class="text-center text-secondary">{{$user->name}}</h1>
<br>
<form method="POST" action="{{route('Usuario.update', $user->id)}} class="user" enctype="multipart/form-data"">
{!! method_field('PUT') !!}
#include('user.form')
<!--Roles-->
<br>
<div class="row justify-content-center text-center">
<div class="col-md-6">
<h5 class="txt-unam text-center text-primary">#lang('edit.Roles')</h5>
#foreach($roles as $id => $name)
<input type="checkbox" value="{{$id}}" {{$user->roles->pluck('id')->contains($id) ? 'checked' : ''}} name="roles[]">
{{ $name }}
#endforeach
</div>
</div>
<br>
<div class="text-center">
<button class="btn btn-warning" type="submit" value="Acttualizar">#lang('edit.Actualizar')</button>
<button class="btn btn-danger" onclick="cancel()" value="Cancelar">#lang('edit.Cancelar')</button>
</div>
</form>
</div>
</body>
And this is the form that I #include in the edit view.
<div class="row justify-content-center py-3">
<div class="col-md-5 mr-2">
<label class="txt-unam text-primary" for="name">#lang('form.Nombre')</label>
<input value="{{isset($user->name)?$user->name:old('name')}}" required type="text" name="name" id="name" class="form-control text-muted">
</div>
<div class="col-md-5">
<label class="txt-unam text-primary" for="email">#lang('form.Correo')</label>
<input value="{{isset($user->email)?$user->email:old('email')}}" required type="text" name="email" id="email" class="form-control text-muted">
</div>
</div>
<div class="row justify-content-center py-1">
<div class="col-md-5 mr-2">
<label class="txt-unam text-primary">#lang('form.Contraseña')</label>
<input value="{{--decrypt($usuario->password) ?? old('password')--}}" class="form-control" type="password" name="password" id="password">
</div>
<div class="col-md-5">
<label class="txt-unam text-primary">#lang('form.Seleccionar')</label>
<select name="department_id" id="department_id" class="form-control">
<option selected disabled value="">#lang('form.Seleccionar')</option>
#foreach ($departments as $department)
<option value="{{$department->id}}">{{$department->department_name}}</option>
#endforeach
</select>
</div>
</div>
When I press the edit button I get the error:
419 Page Expired
Images of the users table structure
If you're getting this error after submitting edit form, then put #csrf after {!! method_field('PUT') !!}
It should like,
<form method="POST" action="{{route('Usuario.update', $user->id)}} class="user" enctype="multipart/form-data"">
{!! method_field('PUT') !!}
#csrf // For lower version use - {{ csrf_field() }}
#include('user.form')
<!--Roles-->
<br>
<div class="row justify-content-center text-center">
<div class="col-md-6">
<h5 class="txt-unam text-center text-primary">#lang('edit.Roles')</h5>
#foreach($roles as $id => $name)
<input type="checkbox" value="{{$id}}" {{$user->roles->pluck('id')->contains($id) ? 'checked' : ''}} name="roles[]">
{{ $name }}
#endforeach
</div>
</div>
<br>
<div class="text-center">
<button class="btn btn-warning" type="submit" value="Acttualizar">#lang('edit.Actualizar')</button>
<button class="btn btn-danger" onclick="cancel()" value="Cancelar">#lang('edit.Cancelar')</button>
</div>
</form>
HTML forms only support POST and GET so if u want to perform an action of updating u need to add #method('PUT') between your opening and closing form tags and then add #csrf still inside your form tags
<form method="POST" action="{{route('user.update', $user->id)}} class="user" enctype="multipart/form-data"">
#method('PUT')
#csrf
</form>

Laravel Error: Missing required parameters

Please help me out. I'm having the missing required parameter's error. This is the form script:
<div class="container">
<div class="row">
<!--first column-->
<div class="col-md-6 col-sm-6 ">
<!-- Default form contact -->
<form class="text-center border border-light p-5" action="{{route('updating', $update->id)}}" enctype="multipart/form-data" method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}" >
#method('PATCH')
<div class="well">
<p class="h4 mb-4">Edit Updates</p>
</div>
<!-- Name -->
<input type="text" name="title" id="defaultContactFormName" class="form-control mb-2" value=" {{ old('title') ?? $update->title }} ">
<!-- Message -->
<div class="form-group">
<textarea class="form-control rounded-0" name="body" id="exampleFormControlTextarea2" rows="5" value="{{ old('title') ?? $update->body }}"></textarea>
</div>
<!-- Send button -->
<button class="btn btn-success btn-block" type="submit">Publish</button>
</form>
</div>
</div>
</div>
And this is my controller and edit function:
public function update(Request $request, $title)
{
$this->validate($request, [
'title'=>'required',
'body'=>'required'
]);
//Publishing Updates
$update = Update::findOrFail($title);
$update->title = $request->input('title');
$update->body = $request->input('body');
$update->save();
return redirect('admin.updates')->with('success', 'Saved');
}
And this is my route:
Route::patch('/updates/{title}/update', 'UpdatesController#update')->name('updating');
I keep getting the error and i don't know where its coming from.

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');

How to update and fetch data of mysql table in laravel 5

i created one view page using laravel 5.2, in that page created one table and fetch data from mysql database. and give dynamic drop down button for Edit and Delete. when i click on delete it will delete the corresponding row from the table.That i done and working properly. I want to do the Edit part. When i click on Edit option it will redirect to one form where i need to fetch all the details from corresponding row into form text field and we can edit the things , when we click on save button it will update the data to the mysql table.
Here i am not able to fetch the details of corresponding row into the form text field. Can anyone help me to do that.
my view page "userAdmin.blade.php" is
#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>
<input type="submit" id="add" name="add" value="Edit" class="button">
</br>
<h4>Create a new User</h4>
<form role="form" method="POST" action="{{ url('userAdmin') }}">
<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="userID" value="{{ old('userID') }}" placeholder="Enter User 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
and Controller page "userController.php" is
<?php
/**
* Created by PhpStorm.
* User: Rahul vp
* Date: 12/05/16
* Time: 11:06 AM
*/
namespace App\Http\Controllers;
use Mail;
use Illuminate\Support\Facades\DB;
use Faker\Provider\DateTime;
use App\User;
use App\Http\Requests\createUserRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Symfony\Component\HttpFoundation\Request;
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');
}
}
then the Editing page where i need to fetch data for updation "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 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
then route.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');
Route::any('user/add', function()
{
return view('user/add');
});
Anyone please help me to do this. response are appreciable.
Your laravel code doesn't follow the common practices or the right way to use laravel.
Please have a look into Resource Controllers
https://laravel.com/docs/5.2/controllers#restful-resource-controllers
Also Eloquent Models
https://laravel.com/docs/5.2/eloquent
Now let's try to solve your problem, add these to your routes
//to show edit form and fetch passed user id info from db
Route::get('user/edit/{id}', 'UserController#edit');
//to get the edited info and save it to db
Route::get('user/update/{id}', 'UserController#update');
Now create a model called user by running this command from your project directory:
php artisan make:model User
Now add these in your controller with other use statements
use App\User; /* User model */
use Illuminate\Database\Eloquent\ModelNotFoundException; /* find or fail error exception class */
Now add these to your controller
// Show Edit page.
public function edit($user_id)
{
try{
//Find the user object from model if it exists
$user= User::findOrFail($user_id);
//Redirect to edit user form with the user info found above.
return view('add',['user'=>$user]);
}
catch(ModelNotFoundException $err){
//redirect to your error page
}
}
// Update user
public function update(Request $request, $user_id)
{
try{
//Find the user object from model if it exists
$user= User::findOrFail($user_id);
//Set user object attributes
//the $request index should match your form field ids!!!!!
//you can exclude any field you want.
$user->description = $request['description'];
$user->contactName = $request['contactName'];
$user->contactPhone = $request['contactPhone'];
$user->timeZone = $request['timeZone'];
//Save/update user.
$user->save();
//redirect to somewhere?
}
catch(ModelNotFoundException $err){
//Show error page
}
}
In your edit view you can access the retrieved user by doing
$user->description //$user->[attribute name]
Since you are not using blade, I believe you can do this, wherever you have old(...) replace it with old(...) || $user->...
except select tags
example:
value="{{ old('contactName') || $user->contactName }}"
for select tags I will give you one example and you need to do the rest by yourself
<select class="form-control" value="{{ old('timeZone') || $user->timeZone}}" name="timeZone" >
<option value="0" {{ $user->timeZone == "0"? 'Selected':''}}>GMT+05:30</option>
<option value="Inactive" {{ $user->timeZone == "Inactive"? 'Selected':''}}>xyz</option>
</select>
Good luck.
Upvotes will be appreciated!

laravel post is not working

I'am working on simple laravel project where user have a registration page.For this I have used two methods register(get method) and postregister(post method).
My code:
public function register() {
return view ( 'auth/register' );
}
public function postregister(Request $req) {
dd("sowmya");
$user = new User ();
$user->name = $req->get ( 'username' );
$user->email = $req->get ( 'email' );
dd($user);
$user->password = Hash::make ( $req->get ( 'password' ) );
$user->remember_token = $req->get ( '_token' );
$user->save ();
return redirect ( '/login' );
}
Get method is working fine.But after submitting form the post method is not calling.even I tried with printing dd("hii") but not displayed. Can someone help me?
#extends('layout') #section('content')<style>
<style>
nav {
visibility: hidden;
}
</style>
<h3 style="margin-top: 70px;" align="center">Signup Page</h3>
<div class="container">
<div class="row">
<div class="register is-Responsive"
style="background-color: rgba(0, 0, 0, 0.3)">
<div id="logo-container"></div>
<div class="col-sm-12 col-md-10 col-md-offset-1">
<form action="/register" id="loginForm" method="post">
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li> #endforeach
</ul>
</div>
#endif {!! csrf_field() !!}
<div class="form-group input-group">
<span class="input-group-addon"><i class="fa fa-user"></i></i></span>
<input class="form-control" type="text" name='username'
placeholder="username" />
</div>
<div class="form-group input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<input class="form-control" type="email" name='email'
placeholder="email" />
</div>
<div class="form-group input-group">
<span class="input-group-addon"><i class="fa fa-key"></i></span> <input
class="form-control" type="password" name='password'
placeholder="password" />
</div>
<div class="form-group input-group">
<span class="input-group-addon"><i class="fa fa-key"></i></span> <input
class="form-control" type="password" name='password_confirmation'
placeholder="confirm password" />
</div>
<div class="checkbox">
<label> <input type="checkbox"> I agree to the <a href="#">Terms
and Conditions</a>
</label>
</div>
<div class="form-group">
<button type="submit" class="btn btn-def btn-block">Signup</button>
</div>
</form>
</div>
</div>
</div>
#endsection
In normal case, without middleware,
Routes:
Route::post ( '/register', 'LoginController#postregister' );
In view:
<form action="{{ URL::to('/register') }}" method="post"></form>
In LoginController:
public function postregister(Request $req)
{
print_r("Came here");die;
}
Change the button tag to input:
<input type="submit" value="Submit" class="btn btn-def btn-block"></input>
Add this inside your form :
<input type="hidden" name="_token" value="{{ csrf_token() }}">
Try this.Good luck.

Categories