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

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

Related

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

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

can't upload audio file to database

I'm trying to upload audio file to database, but nothing happens and i don't get any errors.
controller:
public function store (Request $request)
{
$this->validate(request(), [
'title' => 'required'
]);
$muzika = new Muzika;
if ($request->hasFile('featured_muzika')) {
$daina = $request->file('featured_muzika');
$filename = time(). '.' .$daina->getClientOriginalExtension();
$location = public_path('muzika/' . $filename);
Storage::disk('local')->save($location);
$muzika->daina = $filename;
}
$muzika->daina = $filename;
$muzika->title = $request->title;
$muzika->save();
return redirect('/');
}
this is my form, at first i tried only for title, it was storing in to DB, when i added store method for file it stopped working
{!! Form::open(array('route' => 'muzika.store', 'files' => true)) !!}
{{csrf_field()}}
{!! Form::label('title', 'Title:', ['class' => 'control-label']) !!}
{!! Form::text('title', null, ['class' => 'form-control']) !!}
{{ Form::label('featured_muzika', 'Upload Featured mp3:')}}
{{ Form::file('featured_muzika')}}
{!! Form::submit('Post', ['class' => 'btn btn-primary']) !!}
{!! Form:: close () !!}
when i press submit it only redirects. Database stays empty
In laravel 5.5 you can do
$muzika = new Muzika();
$path = request()->file('featured_muzika')->store('/muzika');
$muzika->daina = $path;
$muzika->save();
make sure your form have enctype="multipart/form-data" set

localhost is currently unable to handle this request. HTTP ERROR 500 with Laravel

I am trying to edit a JSON formatted category with PUT method, so I am using guzzleHttp library to parse json requests and responses with laravel 5.5.
My POST, GET methods are working fine when I am trying to grab or insert data into my server, but I am getting error on PUT & DELETE method.
There are two types of errors I am getting :
localhost is currently unable to handle this request. HTTP ERROR 500
Out Of Memory - Fatal error: Out of memory (allocated 1472200704) (tried to allocate 176128 bytes)
Console Error :
These errors occurs not together just one after another if I request twice in row.
I have trying to change allocated memory, but it did not work !
Here are my procedures to handle a request :
My Controller :
public function update(Request $request, $id)
{
// get the inputs
$inputs = [
"cat_id" => $id,
"cat_name" => $request->input('cat_name'),
"cat_slug" => $request->input('cat_slug'),
"cat_description" => $request->input('cat_description'),
"cat_parent_id" => $request->input('cat_parent_id')
];
// post to the database
$response = $this->categories->update($id, $inputs);
if($response['success']){
$message = $response['message'];
Session::flash('success', 'Category is successfully saved !'.' Server Response Message : '.$message);
return redirect()->route('categories.index');
}else{
$message = $response['message'];
Session::flash('success', 'Category is not successfully saved !'.' Server Response Message : '.$message);
return redirect()->route('categories.index');
}
/////////////////////////////////////////////////
// If the edit page should be shown
//return redirect()->route('categories.edit', $id);
}
My Repository :
public function update($id, $category){
return $this->update("categories/{$id}", $category);
}
And My Custom GuzzleHttpRequest.php :
protected function update($url, $data){
$formatted_data = json_encode($data);
$request = $this->client->request('PUT', $url, [
'body' => $formatted_data
]);
$response = json_decode( $request->getBody()->getContents() , true );
return $response;
}
My Server Accepts JSON formatted inputs : https://rest-banai.herokuapp.com/
Edited :
And My Edit Form :
{!! Form::open(['route' => ['categories.update', $category['cat_id']], 'method' => 'PUT', 'data-parsley-validate' => '']) !!}
<div class="form-group">
{{ Form::label('cat_name', 'Name:') }}
{{ Form::text('cat_name', $category['cat_name'], ['class' => 'form-control', 'placeholder' => 'Enter category name ...', 'required' => '', 'maxlength' => '50']) }}
</div>
<div class="form-group">
{{ Form::label('cat_slug', 'Slug:') }}
{{ Form::text('cat_slug', $category['cat_slug'], ['class' => 'form-control', 'placeholder' => 'Enter a slug word ...', 'required' => '', 'maxlength' => '50', 'data-parsley-type' => 'alphanum']) }}
</div>
<div class="form-group">
{{ Form::label('cat_description', 'Description:') }}
{{ Form::textarea('cat_description', $category['cat_description'], ['class' => 'form-control', 'rows' => '3', 'placeholder' => 'Enter description of the category ...', 'maxlength' => '255']) }}
</div>
<div class="form-group">
{{ Form::label('cat_parent_id', 'Parent Category:') }}
<br />
{{ Form::select('cat_parent_id', $cat_array, null, ['placeholder' => $cat_parent_name]) }}
<br />
</div>
<div class="pull-right">
{{ Form::submit('SAVE', ['class' => 'btn btn-block btn-success btn-sm']) }}
</div>
{!! Form::close() !!}
I am not sure what is I am doing wrong here, any expert, please help me with the issue as I am new with Guzzle and JSON working with Laravel, it will be appreciated.
And If anythings unclear here, please suggest to edit.
Thanks In Advance !
Change your request to
$request = $this->client->request('PUT', $url,['json'=> $data]);
You are using resourceful routes, and yet you have a lot of complexity in your code. This quite frankly in my opinion is completely unnecessary. I will accomplish what you are doing in the following way:
Routes
Route::resource('category', 'CategoryController');
Controller
public function edit(Category $category)
{
return view('category.edit', compact('category'));
}
public function update(Request $request, Category $category)
{
try {
$category->update($request->all()->except(['_token']));
Session::flash('success', 'Category is successfully saved !');
} catch(\Exception $exception) {
Session::flash('error', 'Unable to update category!');
}
return redirect(route('category.index'));
}
HTML
category/edit.blade.php
{!! Form::open(['route' => route('categories.update', $category), 'method' => 'PUT', 'data-parsley-validate' => '']) !!}
<div class="form-group">
{{ Form::label('cat_name', 'Name:') }}
{{ Form::text('cat_name', $category->cat_name, ['class' => 'form-control', 'placeholder' => 'Enter category name ...', 'required' => '', 'maxlength' => '50']) }}
</div>
<div class="form-group">
{{ Form::label('cat_slug', 'Slug:') }}
{{ Form::text('cat_slug', $category->cat_slug, ['class' => 'form-control', 'placeholder' => 'Enter a slug word ...', 'required' => '', 'maxlength' => '50', 'data-parsley-type' => 'alphanum']) }}
</div>
<div class="form-group">
{{ Form::label('cat_description', 'Description:') }}
{{ Form::textarea('cat_description', $category->cat_description, ['class' => 'form-control', 'rows' => '3', 'placeholder' => 'Enter description of the category ...', 'maxlength' => '255']) }}
</div>
<div class="form-group">
{{ Form::label('cat_parent_id', 'Parent Category:') }}
<br />
{{ Form::select('cat_parent_id', $cat_array, null, ['placeholder' => $cat_parent_name]) }}
<br />
</div>
<div class="pull-right">
{{ Form::submit('SAVE', ['class' => 'btn btn-block btn-success btn-sm']) }}
</div>
{!! Form::close() !!}
```

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

Laravel :Attempt to assign property of non-object

Error:
Attempt to assign property of non-object; ErrorException in AdminController.php line 40:
AdminController:
public function createSlider(AdminRequest $request)
{
$input = Request::all();
Sliders::create($input);
if (Request::hasFile('image')) {
$imageName = Request::input('title'). '.' .
$request->file('image')->getClientOriginalExtension();
$request->file('image')->move(
base_path() . '/public/assets/image/', $imageName
);
$input->image = $imageName; //------------> line 40.......
}
$input->save();
}
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() !!}
I've been struggling with this all morning. I want to be able to accept a file upload along with the form information. Renaming the file is not necessary just how i thought i could get this to work. Is there a better way to do this file upload and move?
I changed the format of everything and it worked.
public function createSlider(AdminRequest $request)
{
$slider = new Sliders(array(
'title' => $request->get('title'),
'description' => $request->get('description'),
'link' => $request->get('link')
));
$slider->save();
$imageName = $slider->title .'_gin_slider'. '.' .
$request->file('image')->getClientOriginalExtension();
$request->file('image')->move(
base_path() . '/public/assets/image', $imageName
);
$slider->image = $imageName;
$slider->save();
return redirect('/admin');
}
For further reference: the issue occurs when your controller, router or middleware method does not return a valid response. You should always return a response from your root called method, whether it's actual data or a redirect. In case of middlewares it can be the request itself via Closure.
In case of controllers it should be:
public function index()
{
return response() || redirect()->back();
}
In case of middlewares:
public function handle($request, Closure $next)
{
return $next($request) || response() || redirect()->back();
}
In case of route closures:
Route::get('foo/bar', function(){
return response() || redirect()->back();
});
|| means 'or'

Categories