LARAVEL use single form for both Edit and Insert actions - php

in my application i want to simplify forms and change Form::model to use both of Update and Insert, for have this ability i'm create this route:controller to show View and modrate it:
Route::controller(
'customers' , 'customersController',
array(
'getIndex' =>'customers.index',
'postUpdate'=>'customers.update'
)
);
customersController controller class:
<?php
class customersController extends \BaseController
{
public function getIndex()
{
if ( Auth::check() ){
$customers = new Customers;
return View::make('layouts.customers')->with('customers', $customers);
}
return Redirect::route('dashboard');
}
public function postUpdate($id)
{
print_r( $id);
die;
}
}
?>
in getIndex i can return to view customers.blade.php corretcly and i can be create new variable as an new Customers, in view i'm create below form from created new instance from Customers:
{{ Form::model($customers,array('route' => array('customers.update', $customers->id))) }}
...
{{ Form::submit('UPDATE', array('class'=>'btn btn-default btn-default-small') ) }}
{{ Form::close() }}
now i want to send form values to controler, but after send i get this error:
ERROR:
Missing argument 1 for customersController::postUpdate()

form in view must be like with this code :
{{ Form::model($customers,array('route' => array('customers.update', $customers->id))) }}
and your Form::text must be like with:
{{ Form::text('name', $customers->name, array('class'=>'form-control rtl' ) ) }}
Route:
Route::controller(
'customers', 'customersController',
array(
'getIndex' => 'customers.index',
'postUpdate' => 'customers.update'
)
);
now in controller you can try this code to detect form is update or insert
public function postUpdate()
{
if (Input::get('id')) {
$customer = Customers::find(Input::get('id'));
} else {
$customer = new Customers;
}
...
...
...
}

Related

Despite using 'fillable' and checking all variables, my create method in the controller is not saving input to model

I'm trying to save some data to my model using a form and my controller.
The form looks like this:
<body>
<div class="container">
<h1>Assign days to event</h1>
{{ Form::open(array('url' => 'days')) }}
<div class="form-group">
{{ Form::label('event_name', 'Event Name') }}
{{ Form::select('event_name', $events, null) }}
</div>
<div class="form-group">
{{ Form::label('day_number', 'Number of Days') }}
{{ Form::text('day_number', Input::old('day_number'), array('class' => 'form-control')) }}
</div>
{{ Form::submit('Assign!', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}
</div>
</body>
My Create/Store functions in my Controller looks like this:
namespace StrawDogBuilder\Http\Controllers;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use View;
use Session;
use Redirect;
use StrawDogBuilder\Day;
use StrawDogBuilder\Event;
use Illuminate\Http\Request;
public function create()
{
$events = Event::pluck('id');
return View::make('days.create')
->with('events', $events);
}
public function store()
{
$rules = array(
'event_id' => 'required',
'day_number' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('days/create')
->withErrors($validator)
->withInput(Input::except('password'));
}
else {
$day = new day;
$day->event_id = Input::get('event_name');
$day->day_number = Input::get('day_number');
$day->save();
Session::flash('message', 'You have assigned this event a number of days');
return Redirect::to('days');
}
}
And my Model looks like this
class Day extends Model
{
protected $fillable = ['id','event_name','day_number'];
public function mods()
{
return $this->hasMany('App\Mod');
}
// Get the Event this day is attributed to
public function event()
{
return $this->belongsTo('App\Event');
}
}
The form is created without errors, however when I add values to the fields and hit 'Assign!' it will stay on the same page and will not indicate if it has done anything. Checking the table shows that it hasn't saved the data.
Am I missing something that causes the form to save the data via the controller, and if so what could it be?
First of all revised your form as
{!! Form::open(['route'=>'days.store']) !!}
Then in your controller
public function store(Request $request)
{
$this->validate($request,
array(
'event_id' => 'required',
'day_number' => 'required',
)
);
$day = new Day;
$day->event_id = $request->event_name;
$day->day_number = $request->day_number;
$day->save();
Session::flash('message', 'You have assigned this event a number of days');
return redirect()->route('days');
}

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

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
}

Laravel - using onclick to submit form from checkbox

I have a simple task list project under Laravel.
When I click a checkbox it does not show a checked condition. (The second item is in the true condition in the database and thus shows checked. I cannot uncheck this item) I have searched for an answer to why on the net but cannot find a solution or reason.
Code:
home.blade.php (in views folder) -
#extends('layouts.main')
#section('content')
<h1>Tasks</h1>
<ul>
#foreach ($items as $item)
<li>
{{ Form::open() }}
<input type="checkbox" onClick="this.form.submit()" {{ $item->done ? 'checked' : '' }}>
<input type="hidden" name="id" value="{{ $item->id }}">
{{ $item->name }}
{{ Form::close() }}
</li>
#endforeach
</ul>
#stop
HomeController.php (inControllers folder) -
<?php
class HomeController extends BaseController {
public function getIndex() {
$items = Auth::user()->items;
return View::make('home', array(
'items' => $items
));
}
public function postIndex() {
$id = Input::get('id');
$user_id = Auth::user()->id;
$item = Item::findOrFail($id);
if($item->owner_id == $userId) {
$item->mark();
}
return Redirect::route('home');
}
}
Item.php (in models folder) -
<?php
class Item extends Eloquent {
public function mark() {
$this->$done = $this->done ? false : true;
$this->save();
}
}
routes.php -
<?php
Route::get('/', array('as' => 'home', 'uses' => 'HomeController#getIndex'))->before('auth');
Route::post('/', array('uses' => 'HomeController#postIndex'))->before('csrf');
Route::get('/login', array('as' => 'login', 'uses' => 'AuthController#getLogin'))->before('guest');
Route::post('login', array('uses' => 'AuthController#postLogin'))->before('csrf');
in your code, you never update the model's done value. i assume, you want to change it with the post method. so you'd need to take the value from the checkbox name (e.g. Input::get('box-ID'))
you could also create a checkbox using the form class:
// public function checkbox($name, $value = 1, $checked = null, $options = array())
{{ Form::checkbox('name', 'value', true, ['onClick' => 'alert(123)']) }}
reference: Formbuilder -> checkbox
You should modify your form like this. It works me I hope will work for you also.
{{ Form::open(['route' => ['items.update', $items->id], 'class' => 'form-inline', 'method' => 'put']) }}
Thanks

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