Using controller to edit database on click in Laravel 5.4 - php

I'm trying to have a button pass a query to the database when it's clicked. I'd like to have this set within a Controller that also stores requests and deletes requests. I was able to write to the database using store() and destroy(), but my edit() function gives me routing trouble. What is the best method to edit records using a controller? How would you build the edit() function? Or...should I be using the Update() function? I'm a Laravel/PHP beginner, please explain your answers if you can. Thank you!!
Overview: The project is an employee records table. I want to click a button that changes the employment status of an employee. I already have buttons to add new employee and delete and employee using this same Controller.
This is the route I set for the page:
Route::resource('employees', 'EmployeeController');
This is the front end form code for the button:
$workers = DB::table('employees')->get();
#foreach($workers as $employee)
{!! Form::open(array(
'method' => 'edit',
'route' => [ 'employees.edit', $employee->id]
)
)
!!}
<button type="submit">Release </button>
{!! Form::close() !!}
#endforeach
This is my store function and destroy function:
public function store(Request $request)
{
// Confirm Both Fields Are Not Empty
$this->validate($request, [
'first_name' => 'required',
'last_name' => 'required',
]);
//Add a new employee using the request data
$employee = new Employee;
$employee->first_name = request('first_name');
$employee->last_name = request('last_name');
$employee->position = request('position');
$employee->salary = request('salary');
$employee->hire_date = request('hire_date');
//$employee->attach = request('attach');
//Save it to the database
$employee->save();
//And then redirect back to the Employees page
return redirect('/employees');
}
public function destroy($id)
{
$employee = Employee::find($id);
$destroysignal = $employee->delete();
if($destroysignal) {
return redirect('employees');
}
}

You don't edit records, you update them. In your case you need an update() function in your controller
public function update(Request $request, $id)
{
$employee = Employee::findOrFail($id);
$employee->employment_status = true; //or false or whatever your statuses are
$employee->update();
return redirect()->back()->with('message', 'Employee updated!');
}
In your form, use the update route instead
{!! Form::model($employee, [
'method' => 'PATCH',
'route' => ['employees.update', $employee->id]])
!!}
<button type="submit">Release </button>
{!! Form::close() !!}
When using resource routes, 'route' => [ 'employees.edit', $employee->id] will most like to open a page where you want to edit the object. And the route will be bound to the edit($id) function of your controller.
With that said, the edit route doesn't need a form. A simple anchor would do
Edit Employee

Related

How to pass 2 parameters in a route, but make one hidden in Laravel?

I want to make an edit_Item functionality, but I'm having a little bit of trouble with routing when submiting the edited form. I get this error:
InvalidArgumentException in UrlGenerator.php line 314:
Route [userItems] not defined.
First of all, in my Edit page, I have a form which passes 2 arguments from the Items table (item_id and user_id) to the controller and it looks like this:
{!! Form::model($items, ['action' => ['ItemController#update', $items->id, $items->user_id], 'method' => 'PUT']) !!}
//Form inputs
{{ Form::close() }}
My Update controller looks like this:
public function update($id, $user_id){
// validate
// read more on validation at http://laravel.com/docs/validation
$rules = array(
'title' => 'required',
'description' => 'required|description',
);
// store
$items = Item::find($id);
$items->title = Input::get('title');
$items->description = Input::get('description');
$items->save();
// redirect
Session::flash('message', 'Successfully updated item!');
return Redirect::route('userItems');
}
And my Route with the Update method looks like this:
Route::put('/userItems/{id}/{user_id}', 'ItemController#update');
Now, when I submit I'm currently getting routed to:
http://localhost:8000/userItems/26/3
And I need to get routed to:
http://localhost:8000/userItems/3
Any ideas on how to make the item_id(26) disappear from the route?
You could use an hidden input
Define a hidden field (not visible to a user).
Your form
{!! Form::model($items, ['action' => ['ItemController#update', $items->user_id], 'method' => 'PUT']) !!}
<input type="hidden" name="item_id" value="{{$items->id}}">
//Form inputs
{{ Form::close() }}
Your route
Route::put('/userItems/{user_id}', 'ItemController#update');
Your controller
public function update($user_id){
// validate
// read more on validation at http://laravel.com/docs/validation
$rules = array(
'title' => 'required',
'description' => 'required|description',
);
// store
$item_id = Request::input('item_id');
$items = Item::find($item_id);
$items->title = Input::get('title');
$items->description = Input::get('description');
$items->save();
// redirect
Session::flash('message', 'Successfully updated item!');
return Redirect::route('userItems');
}

Laravel 5.2 all data reset when update 1 single data

I have table dosen and I want to update data to "statusdosen" column.
I have url : ...admin/dosen/status
When I click save, the page redirect to ..admin/dosen and all data in that row has been reset (empty).
This is my view
{!! Form::model($value, ['route' => ['admin.dosen.update', $value->user_id], 'method' => 'PUT']) !!}
<br>
{!! Form::select('statusdosen', array('1' => 'Dikampus', '0' => 'Tidak Dikampus'), null, ['placeholder' => 'Pilih Status'], ['class' => 'form-control']) !!}
<br><br>
!! Form::button('<i class="fa fa-check-square-o"></i> Simpan', ['type' => 'submit', 'class' => 'btn btn-primary btn-sm'] ) !!}
{!! Form::close() !!}
Method :
public function status()
{
$dosen = Dosen::paginate(10);
return view('admin/dosen.status', compact('dosen'));
}
public function update($id)
{
$dosenUpdate = Request::only(['nipy', 'namadosen', 'alamatdosen', 'notelpdosen', 'tempatlahirdosen', 'tanggallahirdosen']);
$user = User::find($id);
$user->dosen()->update($dosenUpdate);
return redirect('admin/dosen')->with('message', 'Data berhasil diubah!');
}
what i want is after i click save it not redirect to other page. do i must create new update method data for 'statusdosen'?
I think you are looking for something along the line of this
public function update(Request $request, $id) {
// Make sure the value is true/1 or false/0
$this->validate($request, ['statusDosen' => 'boolean']);
// Retrieve only the status
$statusDosen = $request->get('statusDosen');
// Update user->dosen()
$user = User::find($id);
$user->dosen()->update($statusDosen);
// Redirect back to the page you came from with your message
return redirect()->back()->with('message', 'Data berhasil diubah!');
}
Ok that explains evreything
$user = User::find($id);
Actually this is same as
Update
dosen
Set
Columnname1=$data, Columnnam2=data2
Where
user_id = $id
This means all rows with this user_id will be updated.
You should be doing like below
public function update($id) {
$dosenUpdate = Request::only(['nipy', 'namadosen', 'alamatdosen', 'notelpdosen', 'tempatlahirdosen', 'tanggallahirdosen']);
//$user= User::find($id); $user->dosen()->update($dosenUpdate);
$dosen = dosen::find($id); // parameter $id must be id of the dosen you want to update
$dosen->update(dosenUpdate);
return back()->with('message', 'Data berhasil diubah!');
}
The return back() will take you back to the previous page but all input value will not be there as the page is being reloaded.
If you do want to keep the data you've two ways
Use return back()->withInput() and store the data to the corresponding input using old.
Use AJAX, and return a response as json.
Eg:
return response()->json(['message'=>'Data berhasil diubah!');

Laravel update method passing through model name instead of ID

I am having an issue with my resource route when calling the update method.
I get this error:
Creating default object from empty value
The controller:
public function update($id)
{
$input = Input::all();
$validation = Validator::make($input, Vehicle::$rules, Vehicle::$messages);
if ($validation->passes())
{
$this->vehicle->update($id, $input);
return Redirect::route('admin.vehicles.index')->with('success', 'Car Updated');
}
return Redirect::back()
->withInput()
->withErrors($validation);
}
repository:
public function update($id, $input)
{
$vehicle = Vehicle::find($id);
$vehicle->VRM = $input['VRM'];
$vehicle->make = $input['make'];
$vehicle->model = $input['model'];
$vehicle->description = $input['description'];
$vehicle->save();
}
Route:
Route::resource('/admin/vehicles', 'VehiclesController');
If I print the ID then it shows {vehicle}.
My form is this:
{{ Form::open(['route' => 'admin.vehicles.update', 'class' => 'form-horizontal edit-vehicle-form', 'method' => 'PATCH']) }}
// input fields etc
{{ Form::close() }}
I think there is something wrong with the form possibly? Since when the error is thrown the URL is:
http://localhost/admin/vehicles/%7Bvehicles%7D
Never had any issues before with using resource routes with CRUD applications and cant see where this is going wrong?
You need the id in update route...
{{ Form::open(['route' => array('admin.vehicles.update', $vehicle->id), 'class' => 'form-horizontal edit-vehicle-form', 'method' => 'PATCH']) }}

Saving/Updating User Profile in Laravel 5

I can't seem to save the updated profile to the database.
In my edit.blade.php:
{!! Form::model($user, ['method' => 'PATCH', 'route' => ['profile.update', $user->company_name] ]) !!}
// fields
{!! Form::submit('Update Profile', ['class' => 'btn btn-primary']) !!}
{!! Form::close() !!}
In my ProfilesController:
public function update($company_name)
{
$user = User::whereCompanyName($company_name)->firstOrFail();
$user->save(); // no validation implemented
flash('You have successfully edited your profile');
return redirect('/');
}
After hitting the update button, it shows the flash message on the homepage but the it's not saving to the database. Im coming from Rails and I feel I need to whitelist something.
The point is, you don't change your user model at all... You retrieve it, and then save it again without setting any fields.
$user = User::whereCompanyName($company_name)->firstOrFail();
// this 'fills' the user model with all fields of the Input that are fillable
$user->fill(\Input::all());
$user->save(); // no validation implemented
If you are using the above method with
$user->fill(\Input::all());
you have to add a $fillable array to your User Model like
protected $fillable = ['name', 'email', 'password']; // add the fields you need
If you explicitly want to set only one or two ( or three....) field you could just update them with
$user->email = \Input::get('email'); // email is just an example....
$user->name = \Input::get('name'); // just an example...
...
$user->save();
If you have tried the anwer Sinmok provided, you probably get the "whooops" page because you used
Input::get('field');
instead of
\Input::get('field');
On your Blade Syntax i assume you use laravel 5.
So as your controller is namespaced you have to add a \ before Input to reference the root namespace ( or put a use statement on top of your class)
Generally on your development server you should enable debugging. Then you have more detailed information about what's going wrong than just the pure.. "whoops... "
In your config/app.php file you can set
'debug' => true;
OR
you have a look at http://laravel.com/docs/5.0/configuration
And use the .env file.
If you use the .env file make sure there is an entry with something like
APP_DEBUG=true
then you can access that value in your config/app.php with
'debug' => env('APP_DEBUG'),
There should be a .env.example in your installation to give you a clue how such a file could look like.
UserController update function look like that :-
public function update(Request $request)
{
$user = Auth::user();
$data = $this->validate($request, [
'name' => 'required',
'email' => 'required',
]);
$user->name = $data['name'];
$user->email = $data['email'];
$user->save();
return redirect('/user_edit/'.Auth::user()->id)->with('success', 'User has been updated!!');
}
Looks like you've not set the submission values to the user object.
Try (Update this is for Laravel 4)
$user = User::whereCompanyName($company_name)->firstOrFail();
$user->field = Input::get("some_field"); // Name of the input field here
$user->save(); // no validation implemented
flash('You have successfully edited your profile');
return redirect('/');
EDIT
Actually, if you're using Laravel 5 it looks like it should be:
$user->field = Request::input('some_field'); // Name of the input field here
$user->save(); // no validation implementedenter code here

Laravel4: Call to a member function update() on a non-object

Following are my codes:
Model:
class Slide extends \Eloquent {
// Add your validation rules here
public static $rules = [
'title' => 'required|between:3,100',
'image' => 'required',
'url' => 'url',
'active' => 'integer'
];
// Don't forget to fill this array
protected $fillable = ['title', 'image', 'url', 'active'];
}
Controller Update Method:
public function update($id)
{
$slide = Slide::find($id);
$validator = Validator::make($data = Input::all(), Slide::$rules);
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
$slide->update($data);
return Redirect::route('admin.slides.index')
->with('message', 'Slide has been updated.')
->with('message-type', 'alert-success');
}
Route:
Route::group(array('prefix' => 'admin'), function() {
# Slides Management
Route::resource('slides', 'AdminSlidesController', array('except' => array('show')));
});
Form in View:
{{ Form::model($slide, array('route' => 'admin.slides.update', $slide->id, 'method' => 'put')) }}
#include('admin/slides/partials/form')
{{ Form::close() }}
Partial Form is simple form, not sure if I need to share it here or not. Let me know.
Error:
Edit page loads perfectly and populates data from db, but when I submit the edit form, I get following error:
Call to a member function update() on a non-object
The following line seems to be creating problems:
$slide->update($data);
I have searched over the internet for solution but nothing is working. Have tried composer dump_autoload, even tried doing everything from scratch in a new project, still same issue. :(
Help please!!
---- Edit ----
Just quickly tried following:
public function update($id)
{
$slide = Slide::find($id);
$slide->title = Input::get('title');
$slide->save();
return Redirect::route('admin.slides.index')
->with('message', 'Slide has been updated.')
->with('message-type', 'alert-success');
}
Now the error:
Creating default object from empty value
----- Solution: -----
The problem was with my form as suggested by #lukasgeiter
I changed my form to following at it worked like a charm:
{{ Form::model($slide, array('route' => array('admin.slides.update', $slide->id), 'method' => 'put')) }}
use $slide->save(); instead of $slide->update($data);
to update a model please read the laravel doc here
To update a model, you may retrieve it, change an attribute, and use the save method:
EX :
$user = User::find(1);
$user->email = 'john#foo.com';
$user->save();
The actual problem is not your controller but your form.
It should be this instead:
{{ Form::model($slide, array('route' => array('admin.slides.update', $slide->id), 'method' => 'put')) }}
This mistake causes the controller to receive no id. Then find() yields no result and returns null.
I recommend besides fixing the form you also use findOrFail() which will throw a ModelNotFoundException if no record is found.
$slide = Slide::findOrFail($id);

Categories