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);
Related
I want to redirect to my new post when I created a new post in Laravel
But I get a ArgumentCountError
Too few arguments to function App\Http\Controllers\ArticlesController::store(), 1 passed in C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54 and exactly 2 expected
How can I fix it? Thanks
web.php
<?php
Route::resource('articles', ArticlesController::class);
Route::get('/', [ArticlesController::class, 'index'])->name('root');
Route::resource('articles.comments', CommentsController::class);
ArticlesController.php
public function store(Request $request, $id) {
$content = $request->validate([
'title' => 'required|max:30',
'content' => 'required|min:10'
]);
//限制只有透過登入才能CREATE文章
auth()->user()->articles()->create($content);
return redirect('articles/'. $id)->with('notice', '文章發表成功!');
}
create.blade.php
<form class="container-fluid" action="{{ route('articles.store') }}" method="post">
Check your store() method. I think it should get only Request $request.
Example
public function store(Request $request) {
$content = $request->validate([
'title' => 'required|max:30',
'content' => 'required|min:10'
]);
//限制只有透過登入才能CREATE文章
$article = Article::create($content); // static is not best practice, only for example
return redirect('articles/'. $article->id)->with('notice', '文章發表成功!');
}
But before using the create method, you will need to specify either a fillable or guarded. Check docs
Presumably you need / have a way of viewing an article anyway, whether it's just been added or not, so in your web.php you would want a GET request to retrieve an article by passing its ID:
Route::get('/article/{id}', [ArticleController::class, 'viewArticle'])-> name('article.view');
Then you would want a POST request to add a new article :
Route::post('/addarticle', [ArticleController::class, 'addArticle'])-> name('article.add');
In your ArticleController, at the end of your addArticle method, once your new article has been created, you can then return a redirect to your "view article" route referencing its name, and passing in the parameter that it expects - the new article's ID - as part of the route, like so :
$article = new Article();
... populate the article's details here ...
return redirect()->route('article.view', ['id' => $article->id]);
I already solved it by my way
remove $id from store() function
just add $article before auth()->user()->articles()->create($content)
$id change to $article->id from redirect()
Example
public function store(Request $request) {
$content = $request->validate([
'title' => 'required|max:30',
'content' => 'required|min:10'
]);
$article = auth()->user()->articles()->create($content);
return redirect('articles/'. $article->id)->with('notice', '文章發表成功!');
}
Thank you
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
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');
}
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']) }}
I am trying to modify a form used for editing and updating data. However when I try submitting the 'edit' form, I keep getting a 'MethodNotAllowedHttpException'. I'm not sure if this is because I am using the 'PUT' method incorrectly or my 'EditAlbumsController.php' file is not defined correctly.
edit-album.blade.php:
{{ Form::model($album, array('method' => 'PUT', 'route' => array('edit_album', $album->album_id))) }}
/* Form code here */
{{ Form::close() }}
routes.php:
Route::get('gallery/album/{id}/edit', array('as'=>'edit_album', 'uses'=>'EditAlbumsController#update'));
EditAlbumsController.php:
class EditAlbumsController extends AlbumsController {
public function __construct()
{
parent::__construct();
}
public function update($id)
{
$input = \Input::except('_method');
$validation = new Validators\Album($input);
if ($validation->passes())
{
$album = Album::find($id);
$album->album_name = $input['album_name'];
/* Additional database fields go here */
$album->touch();
return $album->save();
return \Redirect::route('gallery.album.show', array('id' => $id));
}
else
{
return \Redirect::route('gallery.album.edit', array('id' => $id))
->withInput()
->withErrors($validation->errors)
->with('message', \Lang::get('gallery::gallery.errors'));
}
}
Any help is greatly appreciated!
You need to define the PUT route (you are incorrectly using GET)
Route::put('gallery/album/{id}/edit', array('as'=>'edit_album', 'uses'=>'EditAlbumsController#update'));