Current, I am working on a project using Laravel-5.8. I have a code to update data:
Controller
public function store_external_respondent(StoreAppraisalRespondentExternalRequest $request)
{
$userCompany = Auth::user()->company_id;
$userEmployee = Auth::user()->employee_id;
DB::beginTransaction();
try {
$respondent = AppraisalRespondent::create([
'fullname' => $request->fullname,
'respondent_email' => $request->respondent_email,
'company_name' => $request->company_name,
'is_internal' => 1,
]);
DB::commit();
Session::flash('success', 'Appraisal Respondent created successfully');
return redirect()->route('appraisal.appraisal_respondents.index');
} catch (Exception $ex) {
DB::rollback();
Session::flash('error', 'Action failed! Please try again');
return back();
}
}
route/web.php:
Route::group(['prefix' => 'appraisal', 'as' => 'appraisal.', 'namespace' => 'Appraisal', 'middleware' => ['auth']], function () {
Route::post('appraisal/appraisal_respondents/update_external_respondent/{id?}', 'AppraisalRespondentsController#update_external_respondent')->name('appraisal_respondents.update_external_respondent');
});
When I did php artisan route:list, I got:
| | POST | appraisal/appraisal/appraisal_respondents/update_external_respondent/{id?} | appraisal.appraisal_respondents.update_external_respondent | App\Http\Controllers\Appraisal\AppraisalRespondentsController#update_external_respondent | web,auth
update view blade
<button type="button" class="btn btn-sm btn-info mr-1 edit-respondent-respondent" data-toggle="modal" data-target="#edit_respondent_external{{ $respondentexternal->id }}">Edit</button>
<div class="modal fade" id="edit_respondent_external{{ $respondentexternal->id }}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form action="{{route('appraisal.appraisal_respondents.update_external_respondent',['id'=>$respondentexternal->id])}}" method="post" id="edit_respondent-external-form">
{{ csrf_field() }}
<input type="hidden" name="appraisal_identity_id" value="{{$identities->id}}">
<input type="hidden" name="employee_id" value="{{$employees->id}}">
<input name="_method" type="hidden" value="PUT">
<div class="modal-header">
Update Respondent (External)
</div>
<div class="col-md-12">
<div class="form-group">
<label class="control-label"> FullName:<span style="color:red;">*</span></label>
<input type="text" name="fullname" placeholder="Enter external respondent fullname here" class="form-control" value="{{old('fullname',$respondentexternal->fullname)}}">
#error('fullname')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label class="control-label"> Company:<span style="color:red;">*</span></label>
<input type="text" name="company_name" placeholder="Enter external respondent company here" class="form-control" value="{{old('company_name',$respondentexternal->company_name)}}">
#error('company_name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label class="control-label"> Respondent Email:<span style="color:red;">*</span></label>
<input type="text" name="respondent_email" placeholder="Enter external respondent email here" class="form-control" value="{{old('respondent_email',$respondentexternal->respondent_email)}}">
#error('respondent_email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" id="edit_respondent_external_btn-submit" class="btn btn-success btn-ok">Save</button>
</div>
</form>
</div>
</div>
</div>
When I submitted, I got this error:
405
Method Not Allowed.
Sorry, the page you are looking for could not be found. Go Back
In the console I have:
POST http://localhost:8888/myapp/appraisal/appraisal/appraisal_respondents/update_external_respondent/2 405 (Method Not Allowed)
How do I resolve this?
Also Why is appraisal repeated twice in
POST http://localhost:8888/myapp/appraisal/appraisal/appraisal_respondents/update_external_respondent/2 405 (Method Not Allowed)
Thanks
// STEP 1
Route::post('appra....
// STEP 2
<input name="_method" type="hidden" value="PUT">
So what's wrong?
please use {{method_field('check_your_route_type')}} below {{ csrf_field() }}
e.g : Route::put('url' ... should use {{method_field('PUT')}}
Related
Good Day, I am new in Laravel environment. I am developing a simple school enrollment registration website but having trouble in validation on my controller..
My plan is, when the user will register in the website, username textbox should be validated if the username is already used by other student. i tried every possible tutorial i found in the net but i have no luck...
Here is my page, red circle should be validated if the input username already exist in the database..
Whole code in .blade
<!--Registration start here -->
<form method="Post" action="{{url('store_account_Registration')}}">
#csrf
#if(Session::get('success'))
<div class="alert alert-danger">
{{ Session::get('success')}}
</div>
#endif
#if(Session::get('fail'))
<div class="alert alert-danger">
{{ Session::get('fail')}}
</div>
#endif
<div class="col-sm-12 form-group">
<input type="hidden" class="form-control" name="uniqID3" id="uid" placeholder="Enrollment Registration Number" value="{{ $regid3 }}" >
</div>
<div class="col-sm-12 form-group">
<input type="hidden" class="form-control" name="pfulname3" id="name-f" placeholder="Enrollment Registration Number" required value="{{ $fulname4 }}" >
</div>
<div class="container-fluid" style="margin-bottom: 2em">
<div class="row justify-content-center align-items-center" style="padding: 10px">
<div class="card col-md-5" style="transform: none;>
<div class="card-body">
<div class="alert alert-primary" role="alert" style="margin-top: 1em">
<p>Name: <strong>{{ $fulname4 }}</strong></p>
<p>Enrollment No.: <strong>{{ $regid3 }}</strong></p>
</div>
<input type="hidden" class="hide" id="csrf_token" name="csrf_token" value="C8nPqbqTxzcML7Hw0jLRu41ry5b9a10a0e2bc2">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Username</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-user" aria-hidden="true"></i></span>
</div>
<input type="text" class="form-control" name="username" id="username" placeholder="Username" required value="{{ old('username')}}" >
</div>
<div class="help-block with-errors text-danger">
<span style="color:red">#error('username'){{ $message}}#enderror</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Password</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-lock" aria-hidden="true"></i></span>
</div>
<input type="password" id="password" name="password" pattern="^\S{6,}$" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Must have at least 6 characters' : ''); if(this.checkValidity()) form.password_two.pattern = this.value;" class="form-control" title="Password is needed" required placeholder="Password" >
</div>
<div class="help-block with-errors text-danger">
<span style="color:red">#error('password'){{ $message}}#enderror</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Confirm Password</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-lock" aria-hidden="true"></i></span>
</div>
<input id="password_two" type="password" name="password_two" pattern="^\S{6,}$" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Please enter the same Password as above' : '');" placeholder="Confirm Password" class="form-control" title="Confirm Password is needed" required placeholder="Confirm Password" >
</div>
<div class="help-block with-errors text-danger">
<span style="color:red">#error('password_two'){{ $message}}#enderror</span>
</div>
</div>
</div>
</div>
<div class="row" style="margin-top: 1em" >
<div class="col-md-12" style="margin-bottom: 2em">
<input type="hidden" name="redirect" value="">
<!-- <button type="submit" class="btn btn-primary btn-lg btn-block" name="submit">Save OASIS Account</button> -->
<!-- < <p class="btn btn-primary btn-lg btn-block">Save OASIS Account</p> -->
<button type="submit" class="btn btn-primary btn-lg btn-block">Save OASIS Account</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!--Registration start here -->
</div>
</form>
enter code here
I always got this error..
Here is my code..
my validation in my controller
public function store_account_Registration(Request $request)
{
request()->validate([
'username' => 'required|min:6|unique:TempAccount,AccountName,'
]);
// $this->validator($request->all())->validate();
$current_date = date('Y-m-d H:i:s');
$query = DB::table('TempAccount')->insert([
'RegID'=>$request->input('uniqID3'),
'FullName'=>$request->input('pfulname3'),
'AccountName'=>$request->input('username'),
'Pass'=>$request->input('password'),
'created_at'=> $current_date,
'updated_at'=> $current_date,
]);
if($query){
return back()->with('success', 'Data has been Successfyll inserted');
// return view('pages.enrollment_success');
// return redirect()->route('pages.enrollment_GradeLevelSchoolInfo', ['uniqIDd' => 1]);
// return redirect('enrollment_GradeLevelSchoolInfo');
}
else
{
return back()->with('fail', 'something went wrong');
}
}
my Route in web.php
Route::get('pages',[accountregistration::class, 'index']);
Route::Post('store_account_Registration', [accountregistration::class, 'store_account_Registration']);
my action in form..
The issue is in your form. You are not reaching the correct route at all.
Also you are missing the #csrf token or at least not shown in your print screen
<form action="{{url('store_account_Registration')}}" method="POST">
#csrf
In your validation you can remove the trailing coma after AccountName as well.
So i want to make admin can change any user's password. but i got this error
Call to a member function update() on null
I have no idea what to do
this is my controller
public function resetPassword(Request $req, $id)
{
$req->validate([
'new_password' => ['required'],
'new_confirm_password' => ['same:new_password'],
],
[
'new_password.required' => 'Password Baru Harus Diisi !',
'new_confirm_password.same' => 'Password Baru Harus Sama Dengan Confirm Password !',
]);
User::find($id)->update(['password'=> Hash::make($req->new_password)]);
return redirect('/admin/list_user')->with('status', 'Password Berhasil di Ubah !');
}
this my route
Route::put('/admin/{id}/reset/password', 'PageController#resetPassword')->name('resetPassword');
this is my view modal
<div class="modal fade" id="resetModal" tabindex="-1" role="dialog" aria-labelledby="resetModal" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Reset Password</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="/admin/{id}/reset/password" method="POST">
{{csrf_field()}}
{{ method_field('PUT') }}
<div class="form-group">
<label for="password">Password Baru</label>
<input name="new_password" type="password" class="form-control" id="new_password" required>
</div>
<div class="form-group">
<label for="password">Confirm Password</label>
<input name="new_confirm_password" type="password" class="form-control" id="new_confirm_password" required>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Tutup</button>
<button type="submit" class="btn btn-primary">Buat</button>
</form>
</div>
</div>
</div>
</div>
</div>
<form action="/admin/{id}/reset/password" method="POST">
You're not passing any id. The route picks up '{id}' as the id, then tries to find an User with the id '{id}' and finds none. (->first() returns null).
Just change that opening form tag's action attribute:
<form action="{{ route('resetPassword', ['id' => Auth::id()]) }}" method="POST"> (or instead of Auth::id() the user_id you're trying to update.
You could also use findOrFail($id) instead of find($id) so you'll get a clearer error message if an User is not found.
I am making an application in Laravel. I've created a form to save a model (Repair). But when I save the form, you see it redirecting, but nothing saves. No error or success message is shown?
The store function in the RepairController.php:
public function store(Request $request)
{
$this->validate($request, [
'customer_id' => 'required',
'defect' => 'required',
'stats_id' => 'required'
]);
Repair::create([
'customer_id' => $request->customer_id,
'serial_number' => $request->serial_number,
'model' => $request->model,
'defect' => $request->defect,
'diagnostics' => $request->diagnostics,
'comments' => $request->comments,
'status_id' => $request->status_id
]);
return redirect()->route('repair.index')->with('success',$msg);
}
Repair.php has a fillable:
protected $fillable = ['customer_id', 'serial_number', 'model', 'defect', 'diagnostics', 'comments', 'status_id'];
The create modal:
<div id="newModal" class="modal fade" id="modal-default" tabindex="-1" role="dialog" aria-labelledby="modal-default" aria-hidden="true">
<div class="modal-dialog modal- modal-dialog-centered modal-" role="document">
<div class="modal-content">
<div class="modal-header">
<h6 class="modal-title" id="modal-title-default">Type your modal title</h6>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="{{ route('repair.store') }}" method="POST" id="editForm">
#csrf
<input type="text" name="customer_id" class="form-control" placeholder="Customer ID"><br>
<input type="text" name="serial_number" class="form-control" placeholder="Serial number"><br>
<input type="text" name="model" class="form-control" placeholder="Model"><br>
<input type="text" name="defect" class="form-control" placeholder="Defect"><br>
<div class="form-group">
<label for="Diagnostics">Diagnostics</label>
<textarea name="diagnostics" class="form-control" id="Diagnostics" rows="3"></textarea>
</div>
<div class="form-group">
<label for="Comments">Comments</label>
<textarea name="comments" class="form-control" id="Comments" rows="3"></textarea>
</div>
<input type="text" name="status_id" class="form-control" placeholder="Status ID"><br>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Create repair</button>
<button type="button" class="btn btn-link ml-auto" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
The route in web.php:
Route::resource('repair', 'RepairController');
There might be some validation fails in your data. Can you add the below code above your form and see what it prints.
#if($errors->any())
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
#endif
I am calling a validation request but i am getting this error.
Method Illuminate\Validation\Validator::validateFile, does not exist.
My UserRequest
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use App\Http\Controllers\ProfileController;
class UserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name'=> 'string|required|max:255',
'username'=> 'string|required|max:255|alpha_dash',
'avatar'=>'file,|mimes:jpeg,png,gif,jpg|max:2048',
'email'=> 'email|required|string',
'password'=>'required|min:10|string|confirmed',
'background'=>'file,|mimes:jpeg,png,gif,jpg|max:2048',
'description'=>'string|max:255'
];
}
public function messages()
{
return [
'name.required' => 'A name is required',
'username.required' => 'A username is required',
'email.required' => 'An email is required',
'password.required' => 'A password is required',
'description' => 'A description should be string',
];
}
}
My Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\UserRequest;
use Illuminate\Http\File ;
use App\User;
use Hash;
use Session;
public function update(User $user,UserRequest $request)
{
$user->update(['name'=>request('name'),'username'=>request('username'),'email'=>request('email'),'password'=> Hash::make(request('password')),'avatar'=>$path,'background'=>$background,'description'=>request('description')]);
Session::flash('success', 'You have successfully updated a post!');
return redirect($user->path())->with(['message'=>'Profile updated']);
}
my blade
#extends('layouts.app')
#section('content')
<h1 class="text-gray-700 text-2xl font-bold text-center">Edit Profile</h1>
<div class="mt-5 mb-6">
<img src="{{$user->avatar()}}" alt=""
class="rounded-full mr-2 bottom-0 transform "
width="150px" style="transform: translateX(16.5rem);" >
</div>
<form method="POST" action="{{$user->path() }}" enctype="multipart/form-data">
#csrf
#method('PATCH')
<div id="flip" class="p-5 bg-gray-200">Basic Info</div>
<div id="panel">
<div class="mb-6 mt-6">
<label for="avatar">Select Profile to Upload</label>
<input id="avatar" type="file" class="#error('avatar') is-invalid #enderror" name="avatar">
#error('avatar')
<div class="text-red-800">{{ $message }}</div>
#enderror
</div>
<div class="mb-6">
<label for="name">Name</label>
<input id="name" type="text" class="#error('name') is-invalid #enderror border border-gray-400 p-2 w-full" name="name" value="{{$user->name}}">
#error('name')
<div class="text-red-800">{{ $message }}</div>
#enderror
</div>
<div class="mb-6">
<label for="username">Username</label>
<input id="username" type="text" name="username" class="#error('username') is-invalid #enderror border border-gray-400 p-2 w-full" value="{{$user->username}}">
#error('username')
<div class="text-red-800">{{ $message }}</div>
#enderror
</div>
<div class="mb-6">
<label for="email">Email</label>
<input id="email" type="email" name="email" class="#error('email') is-invalid #enderror border border-gray-400 p-2 w-full" value="{{$user->email}}">
#error('email')
<div class="text-red-800">{{ $message }}</div>
#enderror
</div>
<div class="mb-6">
<label for="password">Password</label>
<input id="password" type="password" name="password" class="#error('password') is-invalid #enderror border border-gray-400 p-2 w-full" >
#error('password')
<div class="text-red-800">{{ $message }}</div>
#enderror
</div>
<div class="mb-6">
<label for="password-confirm">Confirm Password</label>
<input id="password-confirm" type="password" name="password-confirm" class="#error('password-confirm') is-invalid #enderror border border-gray-400 p-2 w-full" >
#error('password-confirm')
<div class="text-red-800">{{ $message }}</div>
#enderror
</div>
</div>
<div id="main" class="p-5 bg-gray-200">Background</div>
<div id="child">
<div class="mb-6 mt-6">
<label for="background">Select Background image to Upload</label>
<input id="background" type="file" class="#error('background') is-invalid #enderror" name="background">
#error('background')
<div class="alert alert-danger">{{ $message }}</div>
#enderror
</div>
<div class="mb-6">
<label for="description">Description</label>
<input id="description" type="text" name="description" class="#error('description') is-invalid #enderror border border-gray-400 p-2 w-full" value="{{$user->description}}">
#error('description')
<div class="alert alert-danger">{{ $message }}</div>
#enderror
</div>
</div>
<div class="mt-6">
<button type="submit" class="bg-blue-500 text-white rounded py-2 px-4 hover:bg-blue-800'">Submit</button>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideToggle("slow");
});
$("#main").click(function(){
$("#child").slideToggle("slow");
});
});
</script>
#endsection
I have tried the solutions available on stack overflow but still none of them work
Does anyone know why am i getting this error?
Any help will be appreciated.
Remove comma in these validation lines.
'avatar'=>'file,|mimes:jpeg,png,gif,jpg|max:2048',
'background'=>'file,|mimes:jpeg,png,gif,jpg|max:2048',
Add password.confirmed in messages array.
'password.confirmed' => 'YOUR ERROR MESSAGE',
I've a store and update method that I would like to use the same modal box to prompt, however I notice that the store method takes the syntax of
<form class="form-horizontal" role="form" method="POST" action="/manage_accounts" novalidate>
whereas my update method,
<form class="form-horizontal" role="form" method="POST" action="/manage_accounts/{{ $user->id }}" novalidate>
<input type="hidden" name="_method" value="PUT">
Is there a way that I can specify which method to use depending on the option chosen, I have two buttons created, each respectively.
<button type="button" class="btn btn-info btn-md" data-toggle="modal" data-target="#form">Register New User</button>
<button class="btn btn-sm btn-warning" type="button"
data-toggle="modal" data-target="#form">Edit <i class="glyphicon glyphicon-edit"></i></button>
Is there a way I can call separately using the same modal box or I have to create two duplicate modal box, one for store, the other for update?
My partial code is shown below ..
blade.php
<div class="well col-xs-9 col-sm-9 col-md-9 col-lg-9 col-xs-offset-1 col-sm-offset-1 col-md-offset-1 col-lg-offset-1">
<div class="row user-row">
<div class="col-xs-2 col-sm-3 col-md-4 col-lg-4">
<h5 style="font-weight: bold">{{ $user->name }}</h5>
</div>
<div class="col-xs-8 col-sm-8 col-md-8 col-lg-8 dropdown-user" data-for=".{{ $user->id }}">
<h5 class="glyphicon glyphicon-chevron-down text-muted pull-right"> </h5>
</div>
</div>
<div class="row user-infos {{ $user->id }}">
<div class="col-xs-12 col-sm-12 col-md-10 col-lg-10 col-xs-offset-0 col-sm-offset-0 col-md-offset-1 col-lg-offset-1">
<div class="panel panel-info">
<div class="panel-heading">
<h2 class="panel-title">User Information</h2>
</div>
<div class="panel-body">
<div class="row">
<div class=" col-md-10 col-lg-10 hidden-xs hidden-sm">
<div class="col-xs-5">User level:</div><div class="col-xs-5"> {{ $user->role->role_description }}</div>
<div class="col-xs-5">Email:</div> <div class="col-xs-5"> {{ $user->email }}</div>
<div class="col-xs-5">Phone number: </div> <div class="col-xs-5"> {{ $user->mobile }} </div>
<div class="col-xs-5">Office extension: </div> <div class="col-xs-5"> [ TO IMPLEMENT ]</div>
</div>
</div>
</div>
<div class="panel-footer">
<button class="btn btn-sm btn-warning btn--edit" type="button"
data-toggle="modal" data-target="#form">Edit <i class="glyphicon glyphicon-edit"></i></button>
<span class="pull-right">
<button class="btn btn-sm btn-danger" type="button">Inactive <i class="glyphicon glyphicon-remove"></i></button>
</span>
</div>
</div>
</div>
</div>
<input type="hidden" name="user_id" value="{{ $user->id }}" />
#endforeach
</div>
#if(Session::has('flash_message'))
<div class="alert alert-success col-xs-9 col-sm-9 col-md-9 col-lg-9 col-xs-offset-1 col-sm-offset-1 col-md-offset-1 col-lg-offset-1">
{{ Session::get('flash_message') }}
</div>
#endif
<div class="col-sm-offset-1 col-sm-2">
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-md" data-toggle="modal" data-target="#form">Register New User</button>
<!-- Modal -->
<div id="form" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">User Information</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" role="form" method="POST" action="/manage_accounts/{{ $user->id }}" novalidate>
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="control-label col-sm-3" for="name">Username:</label>
<div class="col-sm-5 #if ($errors->has('name')) has-error #endif">
<input type="text" class="form-control" type="hidden" id="name" name="name" placeholder="Enter username">
#if ($errors->has('name')) <p class="help-block">{{ $errors->first('name') }}</p> #endif
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="password">Password:</label>
<div class="col-sm-5 #if ($errors->has('password')) has-error #endif">
<input type="password" class="form-control" type="hidden" id="password" name="password" placeholder="Enter login password">
#if ($errors->has('password')) <p class="help-block">{{ $errors->first('password') }}</p> #endif
</div>
</div>
...
controller.php
class ManageAccountsController extends Controller
{
public $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
public function index()
{
$users = User::orderBy('name')->get();
$roles = Role::all();
return view('manage_accounts', compact('users', 'roles'));
}
public function store(StoreUserRequest $request)
{
// validation already handled using this: http://laravel.com/docs/5.0/validation#form-request-validation
$this->userRepository->upsert($request);
Session::flash('flash_message', 'User successfully added!');
return redirect()->back();
}
public function update(StoreUserRequest $request, $id)
{
// validation already handled using this: http://laravel.com/docs/5.0/validation#form-request-validation
$this->userRepository->upsert($request, $id);
Session::flash('flash_message', 'User successfully updated!');
return redirect()->back();
}
}
class UserRepository {
public function upsert($data, $id)
{
// You will also need something like this
if(isset($id))
{
$user = User::find($id);
}
else {
$user = new User;
}
$user->name = $data['name'];
$user->email = $data['email'];
$user->password = Hash::make($data['password']);
$user->mobile = $data['mobile'];
$user->role_id = $data['role_id'];
// save our user
$user->save();
return $user;
}
}