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>
Related
I've got problem with dropdown list.
i want to show a primary key as a dropdown list in view blade , but i can not make the right rout to show it. Have you any ideas how to solve this problem?
this my root
$objects = ['users', 'permissions', 'roles', 'coins','pillars','subtindicators'];
foreach ($objects as $object) {
Route::get("$object", ucfirst(str_singular($object))."Controller#index")->middleware("permission:browse $object")->name("{$object}");
Route::get("$object/datatable", ucfirst(str_singular($object))."Controller#datatable")->middleware("permission:browse $object")->name("{$object}.datatable");
Route::get("$object/add", ucfirst(str_singular($object))."Controller#add")->middleware("permission:add $object")->name("{$object}.add");
Route::post("$object/create", ucfirst(str_singular($object))."Controller#create")->middleware("permission:add $object")->name("{$object}.create");
Route::get("$object/{id}/edit", ucfirst(str_singular($object))."Controller#edit")->middleware("permission:edit $object")->name("{$object}.edit");
Route::post("$object/{id}/update", ucfirst(str_singular($object))."Controller#update")->middleware("permission:edit $object")->name("{$object}.update");
Route::get("$object/{id}/delete", ucfirst(str_singular($object))."Controller#delete")->middleware("permission:delete $object")->name("{$object}.delete");
Route::get("$object/{id}", ucfirst(str_singular($object))."Controller#view")->middleware("permission:view $object")->name("{$object}.view");
Route::get("$object/create", ucfirst(str_singular($object))."Controller#list")->middleware("permission:add $object")->name("{$object}.create");
this my controller
public function add()
{ $strs = DB::table('stargets')->select('*')->get();;
return view('subtindicators.add-edit',compact('strs'));
}
public function update(Request $request, $id)
{
$object = $this->objectModel::find($id);
$object->update([
'skey_name' => $request->skey_name,
'Subtarget_base' => $request->Subtarget_base,
'Subtarget_end' => $request->Subtarget_end,
'subtarget_id' => $request->subtarget_id
]);
if ($request->save == 'browse')
return redirect()->route("{$this->objectName}");
elseif ($request->save == 'edit')
return redirect()->route("{$this->objectName}.edit", ['id' => $object]);
elseif ($request->save == 'add')
return redirect()->route("{$this->objectName}.add");
else
return redirect($request->previous_url);
}
this my blade
#extends('adminlte::page')
#include('bread.title')
#section('main-content')
<div class="container-fluid spark-screen">
<div class="row">
{!! csrf_field() !!}
<form class="form-horizontal" action="{{$actionName=='edit'?route("{$objectName}.update",['id'=>$object->id]):route("{$objectName}.create") }}" method="post">
{!! csrf_field() !!}
<input type="hidden" name="previous_url" value="{{ url()->previous() }}">
<form class="form-horizontal" action="{{ $actionName == 'edit' ? route("{$objectName}.update", ['id' => $object->id]) : route("{$objectName}.create") }}" method="post">
{!! csrf_field() !!}
<input type="hidden" name="previous_url" value="{{ url()->previous() }}">
<div class="box box-solid">
<div class="box-header with-border">
<h3 class="box-title">{{ ucfirst($actionName) }} {{ ucfirst($objectName) }} {{ !empty($object) ? "(ID $object->id)" : '' }}</h3>
<div class="box box-solid">
<div class="box-header with-border">
<h3 class="box-title">{{ ucfirst($actionName) }} {{ ucfirst($objectName) }} {{ !empty($object) ? "(ID $object->id)" : '' }}</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
</div>
</div>
</div>
<div class="box-body">
<div class="form-group">
<label for="" class="col-md-2 control-label">col</label>
<div class="col-md-10">
<input type="text" name="skey_name" class="form-control" maxlength="255" value="{{ !empty($object) ? $object->coin_arname : '' }}" required>
</div>
</div>
<div class="form-group">
<label for="" class="col-md-2 control-label">cl_d</label>
<div class="col-md-10">
<input type="text" name="Subtarget_base" class="form-control" maxlength="255" value="{{ !empty($object) ? $object->coin_enname : '' }}" required>
</div>
</div>
<div class="form-group">
<label for="" class="col-md-2 control-label">cl_e</label>
<div class="col-md-10">
<input type="text" name="Subtarget_end" class="form-control" maxlength="255" value="{{ !empty($object) ? $object->coin_arsymbol : '' }}" required>
</div>
</div>
<div class="form-group">
<label for="" class="form-control">c_i</label>
<div class="col-md-10">
<select class="form-control" name="starget_id">
<option selected disabled value = " ">choos</option>
#foreach($strs as $vis)
<option value="{{$vis->id}}">{{$vis->target_name}}</option>
#endforeach
<!-- <p class="form-control-static">{{ $object->subtarget_id }}</p>-->
</div>
</div>
<div class="form-group has-feedback">
<label for="title">main<span class="text-danger">*</span></label>
<select class="form-control" name="starget_id">
<option selected disabled value = " ">choos</option>
#foreach($strs as $slider2)
<option value="{{$slider2->id}}" {{ $slider2->id== $slider->starget_id ? 'selected' : '' }}>{{$slider2->vname}}</option>
#endforeach
</div>
</div>
</div>
<div class="box-footer">
#include('bread.add-edit-actions')
</div>
</div>
</form> </form>
</div>
</div>
</div>
#endsection
this error what i got
ErrorException (E_ERROR)
Undefined variable: actionName (View: C:\project Last\resources\views\bread\title.blade.php) (View: C:\Ministry Last\resources\views\bread\title.blade.php)
You should forward $actionName variable to your view:
public function add()
{
$strs = DB::table('stargets')->select('*')->get();
$actionName = 'edit';
return view('subtindicators.add-edit',compact('strs', 'actionName'));
}
However this will hardcode the form to being an "edit" form. You must see what you really want with your logic.
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.
I'm creating a file called edit.blade to edit users.
The problem is, when i'm trying to make a list with all roles, Laravel prints the following error:
Undefined variable: roles (View: /home/ubuntu/workspace/resources/views/user/edit.blade.php)
Here is my edit.blade template:
#extends ('adminlte::page')
#section('content')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
<div class="container" style="margin-left:25%">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">
<h2>Editar datos del Usuario</h2>
</div>
<div class="panel-body">
<form class="form-horizontal" method="POST" action="{{ route('user.update', ['user' => $user->id]) }}">
{{ csrf_field() }}
<input type="hidden" name="_method" value="PUT"/>
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<label for="name" class="col-md-4 control-label">
Nombre
</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" name="name" value="{{ $user->name }}" autofocus style=" ">
#if ($errors->has('name'))
<span class="help-block">
<strong style=" ">{{ $errors->first('name') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">
Email
</label>
<div class="col-md-6">
<input id="email" type="text" class="form-control" name="email" value="{{ $user->email }}" autofocus style=" ">
#if ($errors->has('email'))
<span class="help-block">
<strong style=" ">{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<label for="club" class="col-md-4 control-label">
Club
</label>
<div class="col-md-6">
<select name="id_club" >
#foreach($clubs as $club)
<option value="{{$club->id_club}}" class="form-control">{{$club->nombre}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group">
<label for="roles" class="col-md-4 control-label">
Rol
</label>
<div class="col-md-6">
<select name="role_id" >
#foreach($roles as $role)
<option value="{{$role->id}}" class="form-control">{{$role->name}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group">
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Guardar</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
And my this is my UserController that calls the blade template with the relevant variables:
public function edit(User $user)
{
$roles = Role::all();
$clubs = Club::all();
return view('user.edit', ['user' => $user], ['clubs' => $clubs], ['roles' => $roles]);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\User $user
* #return \Illuminate\Http\Response
*/
public function update(Request $request, User $user)
{
$user->save();
$user->roles()->sync([$request->input('role_id')]);
//$user->update($request->all());
return redirect()->route('user.index');
}
I'm including use App\Role; at the top of this file.
Change this:
return view('user.edit', ['user' => $user], ['clubs' => $clubs], ['roles' => $roles]);
to this:
return view('user.edit', ['user' => $user, 'clubs' => $clubs, 'roles' => $roles]);
The view() accepts the data you want to send to the view as an array as a second param.
You can also use view(...)->with(compact('user', 'clubs', 'roles'))
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.
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!