Update Database with Laravel - php

I am trying to update information in my database with Laravel. Not sure what I am doing wrong but I can't seem to find where the problem is. Here is the code for my edit page (This is the page where I would edit information taken from my DB).
{{ Form::open(['url'=>'portfolio/update']) }}
<div>
{{ Form::label('portfolio_title', 'Portfolio Title:') }}
{{ Form::text('portfolio_title',$work->portfolio_title) }}
{{ $errors->first('portfolio_title','<span class="error">:message</span>') }}
</div>
<div>
{{ Form::label('portfolio_description', 'Portfolio Description') }}<br>
{{ Form::textarea('portfolio_description', $work->portfolio_description, ['size' => '50x5']) }}
{{ $errors->first('portfolio_description','<span class="error">:message</span>') }}
</div>
<div>
{{ Form::label('portfolio_content', 'Portfolio Content') }}<br>
{{ Form::textarea('portfolio_content', $work->portfolio_content, ['size' => '50x5']) }}
{{ $errors->first('portfolio_content','<span class="error">:message</span>') }}
</div>
{{ Form::hidden('id',$work->id) }}
<div>
{{ Form::submit('Update Work') }}
</div>
{{ Form::close() }}
I have a controller called PortfolioController that will save info to database and what not.
public function edit($work_title){
$work = Portfolio::wherePortfolio_title($work_title)->first();
return View::make('portfolio/edit', ['work' => $work]);
}
public function update(){
$id = Input::get('id');
$input = Input::except('id');
if( !$this->portfolio->fill($input)->isValid()){
return Redirect::back()->withInput()->withErrors($this->portfolio->errors);
}
$work = Portfolio::find($id);
$work->portfolio_title = Input::get('id');
$work->save();
}
Here is my route that I am working with:
Route::resource('portfolio','PortfolioController');
Route::post('portfolio/update','PortfolioController#update');
I am able to get the form populated with the correct information but when i change something like the title and click update, the page reloads but does not save in the DB. Sometimes I will get an MethodNotAllowedHttpException error. This has been pretty frustrating for me so any help will be greatly appreciated.

Why don't you just actually use your resource route?
First, remove the portfolio/update route. You don't need it.
Then change your Form::open to this:
{{ Form::open(['route' => ['portfolio.update', $work->portfolio_title], 'method' => 'put']) }}
This way you target the update method in your RESTful controller.
Finally change that to use the portfolio_title as identifier and you should be able to remove the hidden id field from your form.
public function update($work_title){}
Please take a look at:
RESTful controllers
Opening a form

Related

Laravel 4.2 - Route not working for searchbar

I have created a Form in a blade template. This form sends a POST request to search.postQuery, so I can get the search query and then do something with it and return a View.
This is the route I have defined:
Route::post('/search/{query}', ['as' => 'search.postQuery', 'uses' => 'SearchController#postQuery'])->where('query', '[a-zA-Z0-9]+');
My form looks like this:
{{ Form::open(array('method' => 'POST', 'route' => array('search.postQuery')) }}
{{ Form::text('searchQuery') }}
{{ Form::submit('Zoeken!') }}
{{ Form::close() }}
This is the method the route calls on POST:
public function postQuery($query)
{
var_dump("Landed here");
}
And finally, the error Laravel poses me with is a NotFoundHttpException.
I also discovered that Laravel is constructing a rather strange URL when I press submit: http://homestead.app/search/%7Bquery%7D
What am I doing wrong? As to my knowledge, I'm not doing something very strange?
This is your error
{{ Form::open(array('route'=>'search.postQuery','method' => 'POST')) }}
{{ Form::text('searchQuery') }}
{{ Form::submit('Zoeken!') }}
{{ Form::close() }}

Directing through form

Im a beginner with laravel. Im following the laracasts tutorial and Im stuck at the part where you access another page with a form by:
{{ Form::open(['url' => 'created']) }}
for example.
Now that leads me to the right url but it gives me
Whoops, looks like something went wrong.
As soon as I type the link manually it works normally.
This is the code of the page where it directs to:
controller:
public function created()
{
return 'hello';
}
Routes:
Route::get('created', 'TestController#created');
View:
#extends('layout')
#section('content')
<h1> Test </h1>
#stop
This is the form of the 1st page:
#extends('layout')
#section('content')
<h1>Create New User</h1>
{{ Form::open(['url' => 'created']) }}
<div>
{{ Form::label('email', 'E-mail:')}}
{{ Form::text('email')}}
</div>
<div>
{{ Form::label('password', 'Password:')}}
{{ Form::password('password')}}
</div>
<div>
{{ Form::submit('Create')}}
</div>
{{ Form::close()}}
#stop
What is going wrong here?
Form open by default links to a post method so what you need is either a post route or a get method. Following should work:
{{ Form::open(['url' => 'created']) }}
// Insert your fields/codes here
{{ Form::close() }}
//Change route method to post
Route::post('created', 'TestController#created');
Please read the documentation here for more details.

Inside create form, how do I route to a nested resource? 'route' => 'user.lesson.store' doesn't work

I've created a nested resource in my routes.php
Route::resource('user', 'UserController');
Route::resource('user.lesson', 'LessonController');
Route::resource('user.lesson.hotspot', 'HotspotController');
And I've tied all user resource actions to the User controller. I've moved on to Lesson, and I'm trying to create a form to create a new lesson.
{{ Form::open(array('route' => 'user.lesson.store')); }}
{{ Form::label('title', 'Title of lesson'); }}
{{ Form::text('title'); }}
{{ Form::label('description', 'Description of lesson'); }}
{{ Form::textarea('description'); }}
{{ Form::submit('Create New Lesson'); }}
{{ Form::close(); }}
However, this produces an action of .../user/%7Buser%7D/lesson. Pointing route at lesson.store produces an error.
What else do I need to do to get this to work?
You need to provide the route with the user key, as the route name that laravel generates will be like user/{user}/lesson/{lesson}
{{ Form::open(array('route' => array('user.lesson.store', $user->getKey()))); }}

How to tackle variables that may not be set when using blade template engine to build forms

Ok, so a long title, but apologies, he only way to describe it without getting the wrong kind of answer.
So, the scenario....
I am creating a site which has a search form of sorts in the header, and therefore on every page. I would like it to retain its previous variables when being used for user convenience, for my convenience I have built the form into the default layout, to save recreating many instances of it.
default.blade.php (Heres the form, with unnecessary markup removed)
{{ Form::open(array('url' => '/search')) }}
{{ Form::select('model', Photo::getAvailableModels(true), $model) }}
{{ Form::select('colour', Photo::getAvailableColours(true), $colour) }}
{{ Form::submit('Go') }}
{{ Form::close() }}
The $model & $colour are variables I am capturing during the post. The problem is, I am getting unset variable errors from Blade on any pages where the user hasn't posted to, so I am literally having to preset them in almost every route or controller across my entire site, just to prevent the errors.
In essence, the system works fine as long as the user is posting, if someone visits the site using a direct link its basically useless.
Obviously I can not have the search form be set to the previously searched results, but that would be bad practice from a usability point of view.
Am I missing something here, surely there has to be a simple solution to this. Thanks for any help.
Create a view composer for your highly used variables:
View::composer(['store.index', 'products.*'], function($view)
{
$model = Input::get('model') ?: 'modelX';
$colour = Input::get('colour') ?: 'colourY';
$view->with('model', $model);
$view->with('colour', $colour);
});
Laravel will send those variables to your views automatically, every time someone hit one of them.
You can put that in your routes file, filters file or, like, me, create a app/composers.php and load by adding
require app_path().'/composers.php';
To your app/start/global.php.
You can check whether variables are set or not with PHP isset():
{{ Form::open(array('url' => '/search')) }}
#if (isset($model) && isset($colour))
{{ Form::select('model', Photo::getAvailableModels(true), $model) }}
{{ Form::select('colour', Photo::getAvailableColours(true), $colour) }}
#else
{{ Form::select('model', Photo::getAvailableModels(true)) }}
{{ Form::select('colour', Photo::getAvailableColours(true)) }}
#endif
{{ Form::submit('Go') }}
{{ Form::close() }}
Or, if your form fields are optional and you need to check separately:
{{ Form::open(array('url' => '/search')) }}
#if (isset($model))
{{ Form::select('model', Photo::getAvailableModels(true), $model) }}
#else
{{ Form::select('model', Photo::getAvailableModels(true)) }}
#endif
#if (isset($colour))
{{ Form::select('colour', Photo::getAvailableColours(true), $colour) }}
#else
{{ Form::select('colour', Photo::getAvailableColours(true)) }}
#endif
{{ Form::submit('Go') }}
{{ Form::close() }}

Laravel - Routing to update error

I encounter a error:
Some mandatory parameters are missing ("users") to generate a URL for route "users.update".
I have this set on my view:
{{ Form::open( array('action' => array('UsersController#update')) ) }}
<div> {{ Form::label('username', 'Username:') }}
{{ Form::text('username', $user->username , array('class' => 'form-control')) }}</div>
<div> {{ Form::label('email', 'Email Address:') }}
{{ Form::text('email', $user->email , array('class' => 'form-control')) }}</div>
<div> {{ Form::label('new_password', 'New Password:') }}
{{ Form::text('new_password', '', array('class' => 'form-control')) }} </div>
<div> {{ Form::label('old_password', 'Old Password:') }}
{{ Form::text('password', '', array('class' => 'form-control')) }} </div>
{{ Form::submit() }}
{{ Form::close() }}
I also have a function in my controller linked to update:
public function update() {
return 'This is an update';
}
And finally, when I check all the routes available in Artisan command, I found that the update has a route to: users/{users}
What's wrong with my codes? I'm trying to update a user and it throws this error.
Your route is defined in a way to expect a variable $users to be passed. because of the: {users}
Instead, you should define it like:
Route::post('users/update', 'UsersController#update');
and then in your function update() get the post variable by:
$users_data = Input::get();
OR
if you want to keep the parameter, redefine the form by passing additional parameter:
{{ Form::open( array('action' => array('UsersController#update', $id)) ) }}
The way you are opening the FORM, it is needs a route paramenter. If you dont want to pass parameters, just use the following:
{{ Form::open(array('action' => 'UsersController#update')) }}
Instead of:
{{ Form::open( array('action' => array('UsersController#update')) ) }}
Even when you're setting a action, you may still need a route for it. I STRONGLY recommend you to always use CLEARED DEFINED routes to your controllers. See if the Resource Controllers helps you, in case you don't wanna to define every god damm route (I DON'T).
And, finally answering your question: I think a
{{ Form::open(array('action' => 'UsersController#update')) }}
...may solve your problem. Hope it helps. Sorry for my bad english! :D

Categories