Update Data in Laravel - 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();
}

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.

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 form submit with route and controller

1.How can i get correct routing into form open phrase.
2.I wanted to generate the URL: dgrs/2014-31-01.
form in only view file: dgrs/show.blade.php
{{ Form::open(array('action'=>'DgrsController#ddgr')) }}
Select Date:
{{ Form::input('date', 'dgrdate', $dt, array('class' => 'input-md')) }}
{{ Form::submit('View', array('class'=>'btn btn-primary')) }}
{{ Form::close() }}
routes.php
Route::match(array('GET', 'POST'), 'dgrs/(:date)', ['as'=>'ddaily', 'uses'=>'DgrsController#ddgr']);
DgrsController.php
public function ddgr($date)
{
$dt=isset($date) ? $date : date("Y-m-d"); //date selection from user
...
return View::make('dgrs.show', compact('dfinal', 'dt'));
//dfinal is db query and dt is selected date back to show.blade.php
}
view is the form file: dgrs/show.blade.php
Please advise.
Here is a solution with jQuery
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
{{ Form::open(array('action'=>'DgrsController#ddgr' , 'id' => 'myFrm')) }}
Select Date:
{{ Form::input('date', 'dgrdate', $dt, array('class' => 'input-md' , 'id' => 'txtDate')) }}
{{ Form::submit('View', array('class'=>'btn btn-primary')) }}
{{ Form::close() }}
<script>
$(document).ready(function(){
$("#txtDate").change(function(){
var baseUrl = "{{ URL::to("dgrs") }}" + "/" + $(this).val();
$("#myFrm").attr("action",baseUrl);
});
});
</script>
so what i have done is when ever date changes form action url is changes according to that date.

eloquent create not inserting everything

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

Laravel pre-filling multiple forms if validation failed

One of the coolest Laravel feature is, Laravel pre-filled the form fields if validation error occurred. However, if a page contain more than one form, and form fields have same name, Laravel pre-filling all forms fields.
For example:
I have a page where i have two forms to create new users or whatever.
<h1>Create user1</h2>
{{ Form::open(array('url' => 'foo/bar')) }}
{{ Form::text('name', null) }}
{{ Form::email('email', null) }}
{{ Form::close() }}
</h1>Create user2</h1>
{{ Form::open(array('url' => 'foo/bar')) }}
{{ Form::text('name', null) }}
{{ Form::email('email', null) }}
{{ Form::close() }}
Controller
class UsersController extends BaseController
{
public function store()
{
$rules = [
'name' => 'required',
'email' => 'required'
];
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails()) {
return Redirect::back()->withInput()->withErrors($validation);
}
}
}
As i didn't fill up the email, Laravel will throw validation error and pre-filling the forms as following:
How to tell Laravel that do not fill-up the second form?
There's no Laravel way of doing this, but you can use HTML basic form arrays to make it work. You need to understand that you have to identify your forms and fields so Laravel knows exactly where the data came from and where to send it back to. If all your fields have the same name how could it possibly know?
This is a proof of concept that will work straight from your routes.php file.
As I did it all and tested here before posting the answer I used Route::get() and Route::post(), to not have to create a controller and a view just to test something I will not use. While developing this you will have to put this logic in a controller and in a view, where I think they are alredy in.
To test it the way it is, you just have to point your browser to the following routes:
http://yourserver/form
and when you push a button it will automatically POST tho the route:
http://yourserver/post
I'm basically giving all forms a number and giving the buttons the number that we will usin in Laravel to get the form data and validate it.
Route::get('form', function()
{
return Form::open(array('url' => URL::to('post'))).
Form::text('form[1][name]', null).
Form::email('form[1][email]', null).
'<button type="submit" name="button" value="1">submit</button>'.
Form::close().
Form::open(array('url' => URL::to('post'))).
Form::text('form[2][name]', null).
Form::email('form[2][email]', null).
'<button type="submit" name="button" value="2">submit</button>'.
Form::close();
});
And here we get the data, select the form and pass all of it to the validator:
Route::post('post', function()
{
$input = Input::all();
$rules = [
'name' => 'required',
'email' => 'required'
];
$validation = Validator::make($input['form'][$input['button']], $rules);
return Redirect::back()->withInput();
});
This is how you use it in a Blade view, now using 3 forms instead of 2 and you can have as many forms as you need:
<h1>Create user1</h2>
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text('form[1][name]', null) }}
{{ Form::email('form[1][email]', null) }}
<button type="submit" name="button" value="1">submit</button>
{{ Form::close() }}
</h1>Create user2</h1>
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text('form[2][name]', null) }}
{{ Form::email('form[2][email]', null) }}
<button type="submit" name="button" value="2">submit</button>
{{ Form::close() }}
</h1>Create user3</h1>
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text('form[3][name]', null) }}
{{ Form::email('form[3][email]', null) }}
<button type="submit" name="button" value="3">submit</button>
{{ Form::close() }}
And you can even use a loop to create 100 forms in blade:
#for ($i=1; $i <= 100; $i++)
User {{$i}}
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text("form[$i][name]", null) }}
{{ Form::email("form[$i][email]", null) }}
<button type="submit" name="button" value="{{$i}}">submit</button>
{{ Form::close() }}
#endfor
Use old input with $request->flash().
https://laravel.com/docs/5.2/requests#old-input

Resources