Laravel can't pass value to controller after submitting to database - php

After submitting to the database and redirecting/reloading the page I get the error Trying to get property 'stockcount1' of non-object. I know it has to do with the product id not being properly passed back but I'm having trouble finding a fix.
show.blade.php
{!! Form::open(['action' => ['App\Http\Controllers\PagesController#addreview', $data['product']->id], 'method' => 'POST']) !!}
{{-- {{ Form::hidden('_method', 'PUT') }} --}}
<div class="form-group">
{{ Form::textarea('description', '', ['class' => 'form-control', 'placeholder' => 'Write your message']) }}
</div>
<div class="form-group">
{{ Form::label('rating', 'Rating') }}
{{ Form::select('rating', ['1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5'], '1') }}
</div>
{{ Form::submit('Submit', ['class' => 'btn btn-primary']) }}
{!! Form::close() !!}
web.php
Route::get('/addreview/{id}', 'App\Http\Controllers\ProductsController#show');
Route::post('/addreview/{id}', 'App\Http\Controllers\PagesController#addreview');
Route::get('/products/{id}', 'App\Http\Controllers\ProductsController#show');
pagescontroller.php
public function addreview(Request $request, $id)
{
$this->validate($request, [
'description' => 'required',
'rating' => 'nullable',
]);
$review = new Review;
$review->rating = $request->input('rating');
$review->reviewerid = auth()->user()->id;
$review->productid = $id;
$review->description = $request->input('description');
$review->save();
$product = Product::find($id);
$reviews = DB::table('reviews')->where('productid', '=', $id)->paginate(10);
$sum = $product->stockcount1 + $product->stockcount2 + $product->stockcount3;
$data = array();
$data['product'] = $product;
$data['stocktotal'] = $sum;
$data['reviews'] = $reviews;
$data['id'] = $id;
return redirect('/products/{$id}')->with('success', 'Review submitted')->with(compact('data'));
//return view('products.show')->with('success', 'Review submitted')->with(compact("data"));
}
productscontroller.php
$product = Product::find($id);
Log::info(print_r($id, true));
$reviews = DB::table('reviews')->where('productid', '=', $id)->paginate(10);
$sum = $product->stockcount1 + $product->stockcount2 + $product->stockcount3;
$data = array();
$data['product'] = $product;
$data['stocktotal'] = $sum;
$data['reviews'] = $reviews;
$data['id'] = $id;
return view('products.show')->with(compact('data'));

Had to change redirect('/products/{$id}') to redirect('/products/'.$id).
Thanks to #user3532758

Related

Trying to store multiple data (row) but it only create 1 row in laravel

I am trying to store array data(saving multiple row) but on single row is being store in my database.
here's my form,
{!! Form::open(['route' => 'warehouse1.store']) !!}
#foreach($order->orderItems as $orderItem)
<input type="number" name="stock_in_qty[]" id="stock_in_qty_{{$orderItem->id}}" class="form-control stock_in_qty" min="1" value="{{$orderItem->quantity}}" data-max="{{$orderItem->quantity}}" onkeyup="check(this);"/>
<script type="text/javascript">
var $orderItem_id = {{$orderItem->id}};
$('#stock_in_qty_'+$orderItem_id).on('mouseup keyup', function () {
$(this).val(Math.min({{$orderItem->quantity}}, Math.max(1, $(this).val())));
});
</script>
{{ Form::date('delivery_date[]',today(), ['class' => 'form-control date', 'style' => 'width:200px;','required']) }}
{!! Form::text('delivery_note[]', null, ['class'=>'form-control']) !!}
{!! Form::hidden('order_id[]', $order->id) !!}
{!! Form::hidden('order_item_id[]', $orderItem->id ) !!}
{!! Form::hidden('company_id[]', $order->company->id) !!}
{!! Form::hidden('stock_out_qty[]',null) !!}
{!! Form::hidden('transfer_to[]', null) !!}
{!! Form::hidden('user_id[]',auth()->user()->id ) !!}
#endforeach
{!! Form::submit('Add to stocks', [ 'class'=>'btn btn-info']) !!}
{!! Form::close() !!}
Here's my store function
public function store(Request $request)
{
$input = $request->all();
for($i=0; $i<= count($input['stock_in_qty']); $i++) {
if(empty($input['stock_in_qty'][$i]) || !is_numeric($input['stock_in_qty'][$i])) continue;
$acceptItem = [
'order_id' => $input['order_id'][$i],
'order_item_id' => $input['order_item_id'][$i],
'delivery_date' => $input['delivery_date'][$i],
'company_id' => $input['company_id'][$i],
'stock_in_qty' => intval($input['stock_in_qty'][$i]),
'stock_out_qty' => $input['stock_out_qty'][$i],
'transfer_to' => $input['transfer_to'][$i],
'delivery_note' => $input['delivery_note'][$i],
'user_id' => $input['user_id'][$i]
];
Warehouse1stocks::create($acceptItem);
return redirect()->route('orders.index');
}
}
dd($acceptItem); result
dd($input) result
what do you think is the possible cause of this? Thank you in advance!
You need to change your controller method to this
public function store(Request $request)
{
$input = $request->all();
$items = [];
for($i=0; $i < count($input['stock_in_qty']); $i++) {
if(empty($input['stock_in_qty'][$i]) || !is_numeric($input['stock_in_qty'][$i])) continue;
$acceptItem = [
'order_id' => $input['order_id'][$i],
'order_item_id' => $input['order_item_id'][$i],
'delivery_date' => $input['delivery_date'][$i],
'company_id' => $input['company_id'][$i],
'stock_in_qty' => intval($input['stock_in_qty'][$i]),
'stock_out_qty' => $input['stock_out_qty'][$i],
'transfer_to' => $input['transfer_to'][$i],
'delivery_note' => $input['delivery_note'][$i],
'user_id' => $input['user_id'][$i]
];
array_push($items, Warehouse1stocks::create($acceptItem));
}
dd($items);
return redirect()->route('orders.index');
}
Because as your code clearly shows below after the creation first acceptItem you will be redirected to the route('orders.index') and not create the other acceptItems
for($i=0; $i<= count($input['stock_in_qty']); $i++) {
if(empty($input['stock_in_qty'][$i]) || !is_numeric($input['stock_in_qty'][$i])) continue;
$acceptItem = [
'order_id' => $input['order_id'][$i],
'order_item_id' => $input['order_item_id'][$i],
'delivery_date' => $input['delivery_date'][$i],
'company_id' => $input['company_id'][$i],
'stock_in_qty' => intval($input['stock_in_qty'][$i]),
'stock_out_qty' => $input['stock_out_qty'][$i],
'transfer_to' => $input['transfer_to'][$i],
'delivery_note' => $input['delivery_note'][$i],
'user_id' => $input['user_id'][$i]
];
Warehouse1stocks::create($acceptItem);
return redirect()->route('orders.index');
}
So you need to move the return statement out of the for loop.

load data to the form by the ID to update in laravel 5.2

I'm trying to populate the data to edit form. Here's my model
public function EditBatch($id,$request){
$data= DB::table('in_batch')
->where('id', $id)
->update(array(
'id'=>$request->input('id'),
'file_name' => $request->input('file_name'),
'batch_type' => $request->input('batch_type'),
'activity_type' => $request->input('activity_type'),
'schedule_time' => $request->input('schedule_time'),
'predecessor' => $request->input('predecessor'),
'priority' => $request->input('priority'),
'batch_remark'=>$request->input('batch_remark'),
'approved_by' => Auth::user()->id,
'approved_on'=>date("Y-m-d H:i:s"),
));
return $data;
}
here's my controller
public function edit($id){
$obatch = new BatchType();
$batch_type = $obatch->GetBatchTypeDropDown();
$batch = new ManageBatch();
$batch->GetBatchById($id);
return view('batch.edit', array('batch'=>$batch,'batch_type'=>$batch_type));
}
here's my view
{!! Form::open (array('url' => array('batch/update',$batch->id), 'class' => 'form-horizontal', 'method' => 'post','id'=>'editbatch')) !!}
<div class="form-group">
{!! Form::label('batch_id', 'batch_id',array('class'=>'col-md-4 control-label')) !!}
<div class="col-md-6">
{!! Form::text('batch_id',$batch->id,array('class'=>'form-control','id'=>'batch_id')) !!}
</div>
</div>
{!! Form::close() !!}
when i trying to load the data to the view as above error is displaying
Undefined property: App\Models\Batch\ManageBatch::$id (View: C:\wamp\www\hutch-in-portal\resources\views\batch\edit.blade.php)
how to solve this ?
thankyou
well i found a solution and the mistake was in the controller method
public function edit($id)
{
$obatch = new BatchType();
$batch_type = $obatch->GetBatchTypeDropDown();
$ouser = new ManageBatchUser();
$batch_user = $ouser->GetUserDropDown();
$batch = new ManageBatch();
$batch_details=$batch->GetBatchById($id);
return view('batch.edit',array('batch_details'=>$batch_details[0],'batch_type'=>$batch_type,'batch_user'=>$batch_user));
}
since i'm passing a single row to the view . i must add the index [0] in return. finally it worked

How to update table with multiple entries. Laravel 5

UPDATED. I have one form that adds data to two different tables (Articles & Deals). An Article has many deals. A deal has one Article. There are multiple deals with different dealnames that the user inputs on the create and edit form. I can create an Article with many Deals fine, and I can populate the edit form with the data from the Deals table, but when I update my 'deals' table using the Articles Controller it just updates every 'dealname' with the last dealname that is inputted. I only need to update the 'dealname' column as all other columns will stay the same. If I remove the dealname/deals part of the form I can update fine.
How can I update the deals table correctly? I know I have to change something in the update function of my Articles Controller.
I'm using Laravel 5.
The Articles Table has: id, title, image, description, address. The Deals table has: id, dealname, article_id, dayID.
Articles Controller- Update
public function update(ArticleRequest $request, $id)
{
$article = Article::find($id);
if( $request->hasFile('image') ){
// photo saving stuff.
}
$article->fill($request->input())->save();
//Get IDs of deals to be updated.
$dealID = Deal::all()->lists('dealname', 'id');
$dealID = $dealID->toArray();
$dealID = array_keys($dealID);
$deals = $request->input('dealname');
foreach($deals as $deal) {
Deal::whereIn('id', $dealID)->update(['dealname' => $deal]);
}
return redirect('/');
}
Form
{!! Form::model($article, ['route' => ['articleUpdate_path', $article->id], 'files' => true, 'method' => 'PATCH']) !!}
{!! Form::label('title','TITLE') !!}
{!! Form::text('title', null, ['class' => 'form-control']) !!}
{!! $errors->first('title','<p class="error">:message</p>')!!}
{!! Form::label('image','PHOTO') !!}
{!! Form::file('image', null, ['class' => 'form-control']) !!}
{!! Form::label('description','DESCRIPTION') !!}
{!! Form::textarea('description', null, ['class' => 'form-control']) !!}
#foreach ($article->deals as $deal)
#if($deal->dayID == '1' )
{!! Form::label('dealname','Monday') !!}
{!! Form::text('dealname[]', $deal->dealname, null, ['class' => 'form-control', 'id' => '1']) !!}
#endif
#if($deal->dayID == '2' )
{!! Form::label('dealname','Tuesday') !!}
{!! Form::text('dealname[]', $deal->dealname, null, ['class' => 'form-control', 'id' => '2']) !!}
#endif
#if($deal->dayID == '3' )
{!! Form::label('dealname','Wednesday') !!}
{!! Form::text('dealname[]', $deal->dealname, null, ['class' => 'form-control', 'id' => '3']) !!}
#endif
#endforeach
{!! Form::label('address','ADDRESS') !!}
{!! Form::text('address', null, ['class' => 'form-control']) !!}
{!! Form::close() !!}
Articles Controller -Store
public function store(ArticleRequest $request)
{
$image_name = $request->file('image')->getClientOriginalName();
$request->file('image')->move(base_path().'/public/images', $image_name);
$article = ($request->except(['image']));
$article['image'] = $image_name;
$article = Article::create($article);
// GET INPUT
$deals = $request->input('dealname');
// GET ID OF ARTICLE
$articleID = $article->id;
// N is the day id that increments
$n = 1;
foreach($deals as $deal) {
Deal::create(['dealname' => $deal, 'article_id' => $articleID, 'dayID' => $n++]);
}
return redirect()->route('articles_path');
}
ARTICLE MODEL
class Article extends Model
{
public function deals()
{
return $this->hasMany('App\Deal');
}
protected $fillable = array('title', 'photo', 'description', 'address');
}
DEAL MODEL
class Deal extends Model
{
public function article()
{
return $this->belongsTo('App\Article')->withTimestamps();
}
protected $fillable = array('dealname', 'article_id', 'dayID');
}
I'm really not sure to fully understand your question, but would something like that could be useful in your case:
public function update(ArticleRequest $request, $id) {
$article = Article::findOrFail($id);
if( $request->hasFile('image') ){
// photo saving stuff.
}
$article->update($request->all());
$article->deals->where('dayID',1)->first()->dealname = $request->input('dealname')[0];
$article->deals->where('dayID',1)->first()->save();
$article->deals->where('dayID',2)->first()->dealname = $request->input('dealname')[1];
$article->deals->where('dayID',2)->first()->save();
$article->deals->where('dayID',3)->first()->dealname = $request->input('dealname')[2];
$article->deals->where('dayID',3)->first()->save();
}
Are they only those 3 dayIds you are using in your form?
EDIT:
You could also try with a for loop. This is untested code, so you might want to optimize it :)
public function update(ArticleRequest $request, $id) {
$article = Article::findOrFail($id);
if( $request->hasFile('image') ){
// photo saving stuff.
}
$article->update($request->all());
for($i = 0; $i < sizeof($request->input('dealname')); $i++) {
$article->deals->where('dayID',($i + 1))->first()->dealname = $request->input('dealname')[$i];
$article->deals->where('dayID',($i + 1))->first()->save();
}
}

Laravel :Trying to get property of non-object on file input

Im trying to do a submit a file with a form submission however I continue to get this error:
Error:
Trying to get property of non-object
at HandleExceptions->handleError('8', 'Trying to get property of non-object', '/Users/plastics1509moore/Desktop/elephant_gin/app/Http/Controllers/AdminController.php', '33', array('request' => object(Request), 'input' => array('_token' => 'y0ExMD4FoH3y1hRX61IOvMW520rn7AEx0UOzrc2R', 'title' => 'lol', 'description' => 'picture of gin one', 'link' => 'www.google.com', 'image' => object(UploadedFile)))) in AdminController.php line 33
I have files set to true. Is the issue the request all?
Here is the Controller function:
public function createSlider(Request $request)
{
$input = Request::all();
if (Input::hasFile('image')) {
$imageName = $input->id . '.' .
$request->file('image')->getClientOriginalExtension();
$request->file('image')->move(
base_path() . '/public/assets/image/', $imageName
);
$input->image = $imageName;
}
Sliders::create($input);
return redirect('/admin');
}
HTML
{!!Form::open(array('url' => 'admin/new_slider', 'files' => true)) !!}
<div class = "form-group">
{!!Form::label('title', 'Title:', ['class' => 'control-label']) !!}
{!!Form::text('title', null, ['class'=> 'input-mini ina tch'])!!}
{!!Form::label('title', 'Description:', ['class' => 'control-label']) !!}
{!!Form::text('description', null, ['class'=> 'input-mini '])!!}
</div>
<div class = "form-group">
{!!Form::label('title', 'Link:', ['class' => 'control-label']) !!}
{!!Form::text('link', null, ['class'=> 'input-mini'])!!}
{!!Form::label('title', 'Image:', ['class' => 'control-label']) !!}
{!! Form::file('image', ['id' => 'imgInp', 'class' => 'prev-upload']) !!}
</div>
<div class = "form-group">
{!!Form::submit('Submit', ['class'=> 'btn btn-default'])!!}
</div>
{!! Form::close() !!}
You are trying to get the id from the input. Your form isn't passing any id so naturally, your input won't have the id.
You can create the slider first and then get the id of the slider like this:
public function createSlider(Request $request)
{
$input = Request::all();
// Create slider
$slider = Sliders::create($input);
if (Input::hasFile('image')) {
// Use the slider id
$imageName = $slider->id . '.' .
$request->file('image')->getClientOriginalExtension();
$request->file('image')->move(
base_path() . '/public/assets/image/', $imageName
);
$input->image = $imageName;
}
return redirect('/admin');
}

Can't upload photo in Laravel 4

I'm trying to add some products to my database and I have to upload photo of this product. I've made a controller and view but when I click Create I don't have any errors but I don't have photo too. I want to upload only jpg,jpeg,gif,png files how can I do it? Here is my code:
Controller:
public function postAddProduct(){
$destinationPath = '';
$filename = '';
$newId = Product::max('id')+1;
$validator = Validator::make(Input::all(), array(
'name' => 'required',
'description' => 'required',
'partner_link' => 'required',
'image' => 'required'
));
if (Input::hasFile('image')) {
$file = Input::file('image');
$destinationPath = public_path().'/uploads/products/';
$filename = $newId.'.'.$file->getClientOriginalExtension();
$uploadSuccess = $file->move($destinationPath, $filename);
}
if($validator->passes()){
$product = new Product;
$product->name = Input::get('name');
$product->description = Input::get('description');
$product->category_id = Input::get('category');
$product->partner_link = Input::get('partner_link');
$product->photo = $filename;
$product->save();
return Redirect::back();
}else{
return Redirect::back()->withErrors($validator)->withInput();
}
}
View:
{{ Form::open(array('url'=>'user/admin/products/addd', 'class'=>'col-md-4', 'style'=> 'float:none; margin: 0 auto', 'id'=>'register-form')) }}
<h2 class="form-signin-heading">Add Product</h2>
{{ Form::text('name', null, array('class'=>'form-control', 'placeholder'=>'Name')) }}
{{ Form::text('description', null, array('class'=>'form-control', 'placeholder'=>'Description')) }}
{{ Form::text('partner_link', null, array('class'=>'form-control', 'placeholder'=>'Partner link')) }}
{{Form::label('category', 'Category: ', array('class' => 'field-name'))}}
<select name="category">
<?php $i = 0; ?>
#foreach($categories as $category)
<optgroup label="{{$category['name']}}">
#foreach($category['subcategories'] as $sub)
<option value="{{$sub->id}}">{{$sub->name}}</option>
#endforeach
</optgroup>
#endforeach
</select>
<div class="clearfix"></div>
{{Form::file('image', array('style' => 'margin-bottom: 10px'))}}
{{ Form::submit('Save', array('class'=>'btn btn-large btn-primary btn-block'))}}
{{ Form::close() }}
You form should have option 'files' set to 'true':
{{ Form::open(array('url' => 'foo/bar', 'files' => true)) }}

Categories