Laravel PHP 4: 'Put' method generates 'MethodNotAllowedHttpException' - php

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

Related

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']) }}

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

Eloquent ORM - update and delete not working

I am working on CRUD for my first Laravel project. Displaying and showing items is working fine.
I tried to update the entry with Query to confirm that I can change values in the table and it worked:
DB::update("UPDATE seasons SET title = 'foo' WHERE ID = 1");
My Problem is that neither updating nor deleting entries will work.
<?php
class SeasonAdminController extends \BaseController
{
// WORKS
public function store()
{
$season = new Season;
$season->title = Input::get('title');
$season->save();
Session::flash('message', 'success!');
return Redirect::to('backend/season');
}
// NOT WORKING
public function update($id)
{
$season = Season::find($id);
$season->title = Input::get('title');
$season->save();
Session::flash('message', 'success!');
return Redirect::to('backend/season');
}
// NOT WORKING
public function destroy($id)
{
Season::destroy($id);
Session::flash('message', 'success!');
return Redirect::to('backend/season/');
}
}
My Route is the following:
Route::resource('backend/season', 'SeasonAdminController');
The form-tag from the edit page:
{{ Form::model($season, array('route' => array('backend.season.update', $season->ID), 'method' => 'PUT')) }}
The form for deleting an entry:
{{ Form::open(array('url' => 'backend/season/' . $value->ID, 'class' => 'pull-right')) }}
{{ Form::hidden('_method', 'DELETE') }}
{{ Form::submit('Löschen', array('class' => 'btn btn-danger')) }}
{{ Form::close() }}
What am I missing here. I appreciate you help, thank you!
The error was that I had "ID" instead of "id" as a primary key in the database table. I am not quite sure why this should not work, but I guess it has to do with the default primary key from the Eloquent Model.
public function update($id){
$inputs = Input::only(array('title'));
if (!$id->update($inputs)) {
Session::flash('message', 'Error!');
}else{
Session::flash('message', 'success!');
}
return Redirect::to('backend/season');
}
public function destroy($id){
if($id){
if($id->delete()){
Session::flash('message', 'Success: Deleted!');
}else{
Session::flash('message', 'Error: Not Deleted!');
}
}
return Redirect::to('backend/season');
}
Try it out.
By the way, the $id is not the season id, can't use find($id) on it because it's an object.
Edit:
You should follow this tutorial
https://www.packtpub.com/books/content/laravel-4-creating-simple-crud-application-hours
Because you do not yet understand how to use models in routes.
Take special attention on how forms are built.
Check your model
class Session extends Model{
protected $table = 'session '; //DB table name
protected $primaryKey = 'Id'; //Primary key Name... some time ORM cant identify the primary key
}

Symfony 2 - Layout embed "no entity/class form" validation isn't working

I'm developing a blog in symfony and i'm stuck with forms that are embed inside the layout. In my case a simple search form.
<div class="b-header-block m-search">
{{ render(controller('YagoQuinoySimpleBlogBundle:Blog:searchArticles')) }}
</div>
To render the form i'm using an embed controller inside the layout twig file.
public function searchArticlesAction(Request $request)
{
$form = $this->createForm(new SearchArticlesType());
$form->handleRequest($request);
if ($form->isValid()) {
// Do stuff here
}
return $this->render('YagoQuinoySimpleBlogBundle:Blog:searchArticles.html.twig', array(
'form' => $form->createView()
));
}
The indexAction is the one that retrieves the form data and filters a list of articles.
public function indexAction(Request $request)
{
$form = $this->createForm(new SearchArticlesType());
$form->handleRequest($request);
if ($form->isValid()) {
$data = $form->getData();
$criteria = array(
'title' => $data['search']
);
} else {
$criteria = array();
}
$articles = $this->getDoctrine()->getRepository('YagoQuinoySimpleBlogBundle:Article')->findBy($criteria, array(
'createDateTime' => 'DESC'
), 5);
return $this->render('YagoQuinoySimpleBlogBundle:Blog:index.html.twig', array('articles' => $articles));
}
SearchArticlesType is a form class
class SearchArticlesType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('search', 'text', array(
'constraints' => new NotBlank()
))
->add('submit', 'submit', array(
'label' => 'Buscar'
));
}
public function getName()
{
return 'searchArticles';
}
}
The problem comes when i submit this form. The indexAction do his part, validating the form and filtering the articles but when the embed controller tries to validate data (just for displaying info or whatever)
$form->handleRequest($request);
if ($form->isValid()) {
// Do stuff here
}
I feel like i'm missing something.
Thank you for your help!
When you call render(controller('your_route')) you are actually making a sub request which means the parameters bags are emptied so your request isn't "handled" by the form.
If you are using 2.4+ you could get the master request from the request stack using ..
/** #var \Symfony\Component\HttpFoundation\RequestStack $requestStack */
$requestStack = $this->get('request_stack');
$masterRequest = $requestStack->getMasterRequest();
And then you could handle that request in your rendered controller as opposed to the current (sub) request like..
$form->handleRequest($masterRequest);
In your: public function searchArticlesAction(Request $request) you're missing second argument on create form
$searchArticle = new SearchArticle(); // I assume this is how you named the Entity, if not just change the entity name
$form = $this->createForm(new SearchArticlesType(), $article);

Laravel 4: undefined variable error when submitting data from the view

I'm trying building a timer app - this form should submit the time (which it does) AND the client name as populated from the database, it looks like this:
{{ Form::open(array('action' => 'TasksController#store', 'name' => 'timer')) }}
{{ Form::select('client', $client , Input::old('client')) }}
{{ Form::hidden('duration', '', array('id' => 'val', 'name' => 'duration')) }}
{{ Form::submit('Submit', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}
My controller that generates this page looks like this:
public function index()
{
$client = DB::table('clients')->orderBy('name', 'asc')->lists('name','id');
return View::make('tasks.index', compact('task', 'client'));
}
I am getting a "Undefined variable: client" when I submit the form. I can't see why.
What am I doing wrong?
EDIT: the store function in my TasksController looks like this:
public function store()
{
$input = Input::all();
$v = Validator::make($input, Task::$rules);
if($v->passes())
{
$this->task->create($input);
return View::make('tasks.index');
}
return View::make('tasks.index')
->withInput()
->withErrors($v)
->with('message', 'There were validation errors.');
}
You are returning the View::make() from your store() function, which is not the 'resourceful' way of doing it.
Your view is expecting to have $client included in it - but because store() does not return a $client - the error is generated.
Assuming you are using a resourceful controller - your store function should look like this:
public function store()
{
$input = Input::all();
$v = Validator::make($input, Task::$rules);
if($v->passes())
{
$this->task->create($input);
return Redirect::route('tasks.index'); // Let the index() function handle the view generation
}
return Redirect::back() // Return back to where you came from and let that method handle the view generation
->withInput()
->withErrors($v)
->with('message', 'There were validation errors.');
}

Categories