eloquent create not inserting everything - laravel

I want to insert a row in my database using the input from a form.
//PersonController
Public function store(){
$input = Input::all();
if(! $this->person->fill($input)->isValid()){
return Redirect::back()->withInput()->withErrors($this->person->messages);
}
$this->person->create($input);
}
//class Person
protected $fillable = ['name', 'group_id', 'email', 'phone', 'address', 'isresponsible'];
public $messages;
public function isValid(){
$validation = Validator::make($this->attributes, static::$rules);
if ($validation->passes()) return true;
$this->messages = $validation->messages();
return false;
}
//Form in View
{{ Form::open(array('action' => 'PersonController#store')) }}
{{ Form::text('name') }}
{{$errors->first('name', '<span class=error>:message</span>')}}
{{ Form::select('group', $groups, Input::old('id')) }}
{{ Form::email('email') }}
{{ Form::text('phone') }}
{{ Form::text('address') }}
{{ Form::checkbox('isResponsible') }}
{{ Form::submit('Create') }}
{{ Form::close() }}
The sql statement generated by
$this->person->create($input)
is missing the foreign key (group_id) and the boolean value (isresponsible)

That's because the names in your form don't match the names of the attributes in the database.
isResponsible ≠ isresponsible
group ≠ group_id
Simply change the names in your form:
{{ Form::select('group_id', $groups, Input::old('group_id')) }}
{{-- ... --}}
{{ Form::checkbox('isresponsible') }}

Related

Laravel issue- "Trying to get property of non-object"

Controller :
$args = array();
$args['name'] = "Robin";
$args['email'] = "asdasd#asdasd.net";
$clientpayments = Payments::getPaymentByClient($id);
$args['activity'] = $clientpayments;
return view('clients.show',["args" => $args]);
View:
{{ $args->name }}
{{ $args->email }}
#if (isset($args['activity']))
#foreach ($args['activity'] as $act)
{{$act->job_name}}
#endforeach
#endif;
So what the issue is is that $activity loop works fine but the $name and $email is returning a non-object error... Any ideas to where I'm going wrong?
Thanks!
Since you're using an array, change this:
{{ $args->name }}
{{ $args->email }}
To:
{{ $args['name'] }}
{{ $args['email'] }}
You are trying to access an object value, but you are sending an array to your view.
$payments = Payments::getPaymentByClient($id);
$args = array([
'name' => 'Robin',
'email' => 'asdasd#asdasd.net',
'activity' => $payments, // Expecting a collection
]);
return view('clients.show', [
"args" => (object) $args // Cast into an object
]);
Blade template (if you have an object)
{{ $args->name }}
{{ $args->email }}
// If your activity is a collection
#foreach ($args->activity as $act)
{{ $act->job_name }}
#endforeach
Blade template (if you have an array)
{{ $args['name'] }}
{{ $args['email'] }}
// If your activity is a collection
#foreach ($args['activity'] as $act)
{{ $act->job_name }}
#endforeach
Got it.
A silly mistake, but I'm just learning Laravel. I was including $args in the View rather than just $name, $email and $activity which worked perfectly.
Thanks anyway.

Update Data in Laravel

This is my code :
Route:
Route::get('/editposts/{id}', function ($id) {
$showpost = Posts::where('id', $id)->get();
return view('editposts', compact('showpost'));
});
Route::post('/editposts', array('uses'=>'PostController#Update'));
Controller :
public function Update($id)
{
$Posts = Posts::find($id);
$Posts->Title = 10;
$Posts->Content = 10;
$Posts->save();
//return Redirect()->back(); Input::get('Title')
}
and View:
#foreach($showpost as $showpost)
<h1>Edit Posts :</h1>
{{ Form::open(array('url'=>'editposts', 'method'=>'post')) }}
Title : {{ Form::text('Title', $showpost->Title) }} <br> Content : {{ Form::text('Content', $showpost->Content ) }} <br> {{ Form::submit('Update') }}
{{ Form::close() }}
#endforeach
but when I want to Update my data i receive an error :
http://localhost:8000/editposts/1
Missing argument 1 for App\Http\Controllers\PostController::Update()
You need to change route:
Route::post('editposts/{id}', 'PostController#Update');
Then the form to:
{{ Form::open(['url' => 'editposts/' . $showpost->id, 'method'=>'post']) }}
Change your post route to:
Route::post('/editposts/{id}', 'PostController#Update');
Done!
Correct the route,specify a parameter
Route::post('editposts/{id}', 'PostController#Update');
Pass the post'id as paramater
{{ Form::open(array('url'=>'editposts/'.$post->id, 'method'=>'post')) }}
Title : {{ Form::text('Title', $showpost->Title) }} <br> Content : {{ Form::text('Content', $showpost->Content ) }} <br> {{
Form::submit('Update') }}
{{ Form::close() }}
Notice $post->id
First declare your route:
Route::post('/editposts/{id}', array('uses'=>'PostController#Update'));
Then update your form url:
{{ Form::open(['url' => url()->action('PostController#Update', [ "id" => $showpost->id ]), 'method'=>'post']) }}
This is assuming your model's id column is id
(Optional) You can also use implicit model binding :
public function Update(Posts $id) {
//No need to find it Laravel will do that
$id->Title = 10;
$id->Content = 10;
$id->save();
}

serialization of 'closure not allowed' Error

Below is the code from my product view:
{{ Form::open(array('url'=>'admin/products/create' , 'files'=>true)) }}
<p>
{{ Form::label('category_id' , 'Category') }}
{{ Form::select('category_id' , $categories) }}
</p>
<p>
{{ Form::label('title') }}
{{ Form::text('title') }}
</p>
<p>
{{ Form::label('description') }}
{{ Form::textarea('description') }}
</p>
<p>
{{ Form::label('height') }}
{{ Form::text('height' , null , array('class'=>'form-price')) }}
</p>
<p>
{{ Form::label('width') }}
{{ Form::text('width' , null , array('class'=>'form-price')) }}
<!--{{ Form::label('image' , 'Choose an image') }}
{{ Form::file('image') }}-->
</p>
<p>
{{ Form::label('length') }}
{{ Form::text('length' , null , array('class'=>'form-price')) }}
</p>
<p>
{{ Form::label('color') }}
{{ Form::text('color' , null , array('class'=>'form-price')) }}
</p>
<p>
{{ Form::label('material') }}
{{ Form::text('material' , null , array('class'=>'form-price')) }}
</p>
{{ Form::submit('Create Product' , array('class'=>'secondary-cart-btn')) }}
{{ Form::close() }}
and below is the code from my product controller:
<?php
/**
*
*/
class ProductsController extends BaseController {
public function __construct() {
$this->beforeFilter('csrf' , array('on'=>'post'));
}
public function getIndex() {
/* NOTE :: the categories array is being
created so that the products index page
can have access to all the availability
categories */
$categories = array();
foreach (Category::all() as $category) {
$categories[$category->id] = $category->name;
}
return View::make('products.index')
->with('products' , Product::all())
->with('categories' , $categories);
}
public function postCreate() {
$validator = Validator::make(Input::all() , Product::$rules);
if($validator->passes()) {
$product = new Product;
$product->category_id = Input::get('category_id');
$product->title = Input::get('title');
$product->description = Input::get('description');
$product->height = Input::get('height');
$product->width = Input::get('width');
$product->length = Input::get('length');
$product->color = Input::get('color');
$product->material = Input::get('material');
/* code for saving the image */
/* $image = Input::file('image');
$filename = date('Y-m-d-H-i-s')."-".$image->getClientOriginalName();
$path = public_path('img/products/' .$filename);
Image::make($image->getRealPath())->resize(468, 249)->save($path);
$product->image = 'img/products/'.$filename; */
/*end of code for saving the image */
$product->save();
return Redirect::to('admin/products/index')
->with('message' , 'Product created');
}
return Redirect::to('admin/products/index')
->with('message' , 'something went wrong')
->withError($validator)
->withInput();
}
public function postDestroy() {
$product = Product::find(Input::get('id'));
if ($product) {
$product->delete();
return Redirect::to('admin/products/index')
->with('message' , 'product has been deleted');
}
return Redirect::to('admin/products/index')
->with('message' , 'something went wrong , Please try again');
}
}
?>
Now when i fill the values in the form and click on submit i get a error as follows :
Error image
serialization of 'closure not allowed' , on googling a bit i found the following helpful thread:
Related thread,
the accepted solution is not applicable to me and i tried the solution in the second answer and i still have the same error.
I still don't understand what could be the cause of this error or what am i doing wrong ? can anybody explain ?
Unless it is a typo in the code you have posted, the accepted solution to the related question you posted does relate to you.
On your return statement, you have ->withError($validator), this should be ->withErrors($validator) (you're missing the 's').

Laravel 4 :: custom validation error message is not displaying?

I'm trying to create an online form and to display my own error messages. But for some reason it's not working correctly. Here's my controller code, CategoryController.php:
class CategoryController extends BaseController
{
public function add()
{
return View::make('admin');
}
public function validate_add()
{
$rules = array('category_name' => 'Required|Alpha|Min:4');
$messages = array('category_name.Required' =>'Please enter the category name');
$input = Input::all();
$validator = Validator::make($input, $rules, $messages);
if ($validator->fails())
{
return Redirect::to('admin')->withErrors($validator)->withInput(Input::all());
}
else
{
echo '<h1>WOW! your are are awesome!!! <3<h1> ';
}
}
}
And the admin.blade.php is following:
#extends('common')
#section('body')
<h1>Add Category</h1>
{{ HTML ::ul($errors->all(), array('class'=>'errors')) }}
{{ Form::open(array( 'url'=>'admin', $title="Admin Control Panel")) }}
<p>
{{ Form::label('Category Name:') }}
{{ Form::text('category_name', Input::old('category_name')) }}
</p>
<p>
{{Form::label('Parent Category') }}
{{ Form::select('Network', array('0' => 'Maincategory')) }}
</p>
<p>
{{ Form::submit('Submit') }}
</p>
{{ Form::close() }}
#stop
Interesting - I tried this on my local Laravel project and it looks like although you can specify your rules in mixed case, you need to specify the custom messages in lower case.
So if you changed your rules and your message override to; 'required' instead of 'Required' etc., it should work.

HasMany relationship old input

I have a model Category. Category has many Localization. When I store Category, I have these inputs:
{{ Form::text('title[en]', Input::old('title')) }}
{{ Form::text('title[ru]', Input::old('title')) }}
Which I store like this in my controler:
// Gett all inputs
$inputs = Input::all();
// Create resource
$item = Category::create([]);
// Create localization
foreach(Input::get('title') as $locale => $title)
{
$locale = new Localization(['locale' => $locale, 'title' => $title]);
$locale = $item->localization()->save($locale);
}
That works great but what is the best practise for updating such relationships? Currently I'm trying that with Form::model binding.
#foreach($locales as $key => $locale)
{{ Form::text('title['.$locale.']', $model->translate($locale)->title, ['class' => 'form-control']) }}
#endforeach
I have no idea how Input::old could work in this situation, so now I'm using $model->translate($locale)->title to get the correct value. Basically the updating/validation part doesn't really work. What you could suggest to change to validate such relationship and update it?
Today I found a working solution storing/updating relationships with validation. I hope it's the best/simplest way to do that. I created a new array with inputs for validation and changed in the view errors accordingly.
This is my update controller.
public function update($id)
{
// Find resource
$item = Category::find($id);
foreach(Input::get('title') as $locale => $title)
{
$v['title_'.$locale] = $title;
}
// Attempt validation
if($item->validate($v))
{
foreach(Input::get('title') as $locale => $title)
{
$localization = $item->translate($locale);
$localization->title = $title;
$localization->save();
}
return Redirect::action('AdminCategoryController#edit', [$item->id]);
}
else
{
// Failure, get errors
$errors = $item->errors();
return Redirect::back()
->withInput()
->with('errors', $errors);
}
}
And this is the update view;
{{ Form::model($model, ['action' => ['AdminCategoryController#update', $model->id], 'method' => 'PUT']) }}
#foreach($locales as $key => $locale)
<div id="{{ $locale }}">
<div class="form-group">
{{ Form::label('title['.$locale.']', _('admin.title_'.$locale)) }}
{{ Form::text('title['.$locale.']', $model->translate($locale)->title, ['class' => 'form-control']) }}
#if($errors->has('title_'.$locale))
<div class="help-block alert alert-danger">{{ $errors->first('title_'.$locale) }}</div>
#endif
</div>
</div>
#endforeach
{{ Form::close() }}
This way you can easily CRUD, validate all types of relationships (input arrays) in Laravel.

Resources