Laravel can't save photo - php

I have function code below but it won't save photo not in database nor in file path.
Code
public function store(Request $request)
{
$this->validate($request, array(
'name' => 'required',
'price' => 'required|numeric',
'type_id' => 'required|numeric',
'photo' => 'required',
));
$item = new Menu;
$item->name = $request->input('name');
$item->price = $request->input('price');
$item->type_id = $request->input('type_id');
if ($request->hasFile('photo')) {
$photo = $request->file('photo');
$filename = 'MenuItem' . '-' . time() . '.' . $photo->getClientOriginalExtension();
$location = public_path('images/'. $filename);
Image::make($photo)->resize(500, 500)->save($location);
$item->photo = $filename;
}
$item->save();
Session::flash('success', 'Menu Item Saved Successfully.');
return redirect()->back();
}
dd($request->all()); of code above
array:5 [▼
"_token" => "awAvc7F8lOv9vKkfwyiTFj7jnQGszv8xjLQxcwRH"
"name" => "test"
"price" => "100"
"photo" => "air putih.jpg"
"type_id" => "1"
]
Any idea?
Update
Based on the Nabil Farhan answer below I was forgot about enctype="multipart/form-data" but now I'm getting
Intervention \ Image \ Exception \ NotReadableException
Unable to find file ().
Still not able to save my photo.
Update 2
I dd my requests again, now after adding enctype="multipart/form-data" it becomes strange:
array:5 [▼
"_token" => "awAvc7F8lOv9vKkfwyiTFj7jnQGszv8xjLQxcwRH"
"name" => "kerupuk"
"price" => "2000"
"type_id" => "3"
"photo" => UploadedFile {#805 ▼
-test: false
-originalName: "kerupuk.jpg"
-mimeType: "image/jpeg"
-error: 0
#hashName: null
path: "C:\Windows\Temp"
filename: "phpB195.tmp"
basename: "phpB195.tmp"
pathname: "C:\Windows\Temp\phpB195.tmp"
extension: "tmp"
realPath: false
aTime: 2019-02-12 04:57:39
mTime: 2019-02-12 04:57:39
cTime: 2019-02-12 04:57:39
inode: 0
size: 43933
perms: 0100666
owner: 0
group: 0
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
linkTarget: "C:\Windows\Temp\phpB195.tmp"
}
]
Why my photo field becomes like that?!
anyway here is my form in blade:
{{ Form::open(array('route' => 'menus.store', 'files' => true)) }}
<div class="row">
<div class="col-md-12">
<h5>Name</h5>
{{ Form::text('name', null, array('class' => 'form-control')) }}
</div>
<div class="col-md-12">
<h5>Price</h5>
{{ Form::number('price', null, array('class' => 'form-control')) }}
</div>
<div class="col-md-12">
<h5>Photo</h5>
{{ Form::file('photo', array('class' => 'form-control', 'id' => 'photo')) }}
</div>
<div class="col-md-12">
<h5>Type</h5>
<select name="type_id" id="type_id" class="form-control">
<option value="">-- Select --</option>
#foreach($types as $type)
<option value="{{$type->id}}">{{$type->name}}</option>
#endforeach
</select>
</div>
<div class="col-md-12 mt-2">
{{ Form::submit('Save', array('class' => 'btn btn-primary')) }}
</div>
</div>
{{ Form::close() }}

The "photo" => "air putih.jpg" should not be a string. It should have some more information regarding file.
I think the problem is in your blade file. Please check if you have used enctype='multipart/form-data' in your form tag.
EDIT
Change this
Image::make($photo)->resize(500, 500)->save($location);
To this
Image::make($photo->getRealPath())->resize(500, 500)->save($location);

Try to change this line
Image::make($photo)->resize(500, 500)->save($location);
Image::make($photo->getRealPath())->resize('200','200')->save($location);
Your realpath is false check config

You should try this:
Your view file like this:
{!! Form::open(['route' => 'menus.store', 'class' => 'form-horizontal', 'role' => 'form', 'method' => 'post','files'=>true]) !!}
<div class="row">
<div class="col-md-12">
<h5>Name</h5>
{{ Form::text('name', null, array('class' => 'form-control')) }}
</div>
<div class="col-md-12">
<h5>Price</h5>
{{ Form::number('price', null, array('class' => 'form-control')) }}
</div>
<div class="col-md-12">
<h5>Photo</h5>
{{ Form::file('photo', array('class' => 'form-control', 'id' => 'photo')) }}
</div>
<div class="col-md-12">
<h5>Type</h5>
<select name="type_id" id="type_id" class="form-control">
<option value="">-- Select --</option>
#foreach($types as $type)
<option value="{{$type->id}}">{{$type->name}}</option>
#endforeach
</select>
</div>
<div class="col-md-12 mt-2">
{{ Form::submit('Save', array('class' => 'btn btn-primary')) }}
</div>
</div>
{{ Form::close() }}
Your controller function like this:
use Input;
public function store(Request $request)
{
$this->validate($request, array(
'name' => 'required',
'price' => 'required|numeric',
'type_id' => 'required|numeric',
'photo' => 'required',
));
$item = new Menu;
$item->name = $request->input('name');
$item->price = $request->input('price');
$item->type_id = $request->input('type_id');
if ($request->hasFile('photo')) {
$photo = Input::file('photo');
$filename = 'MenuItem' . '-' . time() . '.' . $photo->getClientOriginalExtension();
$location = public_path('images/'. $filename);
$img = Image::make($photo->getRealPath());
$img->resize(500, 500, function ($constraint) {
$constraint->aspectRatio();
})->save($location);
$item->photo = $filename;
}
$item->save();
Session::flash('success', 'Menu Item Saved Successfully.');
return redirect()->back();
}

Related

How to insert multiple form in laravel 5.4

I have problem with input multiple form, in my case, result array is like this
{
approval_activities": null,
"remark_id": [
"9",
"10"
],
"name_remark": [
"Capex",
"Asset"
],
"label_remark": [
"Capex",
"Asset"
],
"description_remark": [
"Capex",
"Asset"
],
"filter_logic_remark": [
null,
null
],
"default_remark": [
"Capex",
"Asset"
],
"weight_remark": [
"5",
"1"
]
I try to insert it to other table using foreach, but I have error message Array to string conversion
$asset = Asset::create([,'approval_activities' => $request->approval_activities]);
$arr[] = $request->all();
foreach ($arras $req) { //remark
$i = 0;
$pret = [
'asset_id' => $asset->id,
'remark_id' => $req[$i]['remark_id'],
'name' => $req[$i]['name_remark'],
'label' => $req[$i]['label_remark'],
'description' => $req[$i]['description_remark'],
'filter_logic' => $req[$i]['filter_logic_remark'],
'default' => $req[$i]['weight_remark']
];
$i++;
}
RemarkAsset::create($pret);
this is my form in blade, in this code I use [] in name for send an array to controller, the result from this code is like JSON above.
{!! Form::label('approval_activities', 'Approval Jenis Kegiatan', ['class' => 'col-sm-2 control-label']) !!}
<div class="col-sm-4 {{ $errors->has('approval_activities') ? 'has-error' : ''}}">
<select id="approval_activities" name="approval_activities" class="form-control select2_demo_1"
data-placeholder="Select Approval Jenis Kegiatan">
<option value="">Select Approval Jenis Kegiatan</option>
<option value="Aktivasi">Aktivasi</option>
</select> {!! $errors->first('approval_kegiatan', '<p class="help-block">:message</p>') !!}
</div>
<div class="form-group">
{!! Form::label('name', 'Name', ['class' => 'col-sm-2 control-label']) !!}
<div class="col-sm-4 col-xs-12 {{ $errors->has('name') ? 'has-error' : ''}}">
{!! Form::text('name_remark[]', $item->name, ['class' => 'form-control','placeholder'=>'Name']) !!}
{!! $errors->first('name', '<p class="help-block">:message</p>') !!}
</div>
{!! Form::label('label', 'Label', ['class' => 'col-sm-2 control-label f-w-none']) !!}
<div class="col-sm-4 col-xs-12 {{ $errors->has('label') ? 'has-error' : ''}}">
{!! Form::text('label_remark[]', $item->name, ['class' => 'form-control','placeholder'=>'Label']) !!}
{!! $errors->first('label', '<p class="help-block">:message</p>') !!}
</div>
</div>
My expect is inserting $asset to table asset just have 1 record, and the remark is inserted to table remark, if I have two remark_id or other like JSON above then the record in table remark is two.
The $req[$i]['name_remark'] would work if the array looked like the following, where there is a name_remark for every $i.
{
"name_remark": "Capex"
},
{
"name_remark": "Asset"
}
In your case I believe you want $req['name_remark'][$i] instead.

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() !!}
```

How can I make a search that is filtered by multiple inputs in Laravel 4.2?

I want this form to search multiple fields. How can I aggregate these search terms and filter them by their appropriate fields?
For example, if the user types "Book" into the textsearch field, and then selects "Assigned" from the status dropdown, the page should return all requests containing 'book' in the subject or details field, and 'assigned' in the status field.
I have the following form in my Laravel 4.2 Application:
{{ Form::open(['route' => 'requests.search']) }}
<!-- Text Search Form Input -->
<div class="form-group">
{{ Form::label('textsearch', 'Text Search:') }}
{{ Form::text('textsearch', $query, ['class' => 'form-control']) }}
{{ Form::hidden('search', 'text') }}
</div>
<!-- Status Form Input -->
<div class="form-group">
{{ Form::label('status', 'Status:') }}
{{ Form::select('status', $statuses, null, ['class' => 'form-control']) }}
</div>
<!-- Category Form Input -->
<div class="form-group">
{{ Form::label('category', 'Category:') }}
{{ Form::select('category', $categories, null, ['class' => 'form-control']) }}
</div>
<!-- Teamleader Form Input -->
<div class="form-group">
{{ Form::label('teamleader', 'Team Leader:') }}
{{ Form::select('teamleader', $projectmembers, null, ['class' => 'form-control']) }}
</div>
<!-- Requestid Form Input -->
<div class="form-group">
{{ Form::label('requestid', 'Request ID:') }}<br/>
<span>Between:</span>
{{ Form::text('requestidstart', null, ['class' => 'form-control', 'style' => 'width:100%;']) }}
<span>And:</span>
{{ Form::text('requestidend', null, ['class' => 'form-control', 'style' => 'width:100%;'])}}
</div>
<!-- Requestdate Form Input -->
<div class="form-group">
{{ Form::label('requestdate', 'Request Date:') }}<br/>
<span>From:</span>
{{ Form::text('requestdatestart', null, ['class' => 'form-control etadatepicker', 'style' => 'width:100%;']) }}
<span>To:</span>
{{ Form::text('requestdateend', null, ['class' => 'form-control etadatepicker', 'style' => 'width:100%;'])}}
</div>
<!-- Requestduedate Form Input -->
<div class="form-group">
{{ Form::label('requestduedate', 'Due Date:') }}<br/>
<span>From:</span>
{{ Form::text('requestduedatestart', null, ['class' => 'form-control etadatepicker', 'style' => 'width:100%;']) }}
<span>To:</span>
{{ Form::text('requestduedateend', null, ['class' => 'form-control etadatepicker', 'style' => 'width:100%;'])}}
</div>
{{ Form::submit('Search') }}
{{ Form::close() }}<br/>
Controller:
$requestresponsetype = ['' => ''] + RequestResponseType::lists('description', 'description');
$projectmembers = ['' => ''] + RequestProjectMember::lists('first_name', 'first_name');
$statuses = ['' => ''] + RequestStatus::lists('description', 'description');
$categories = ['' => ''] + RequestCategory::lists('description', 'description');
$query = Input::get('textsearch');
$requests = DataRequest::where("subject", "LIKE", "%$query%")->orWhere("details", "LIKE", "%$query%")->orWhere("id","LIKE","%$query%")->paginate(10);
return View::make('requests.index', ['requests' => $requests, 'statuses' => $statuses, 'requestresponsetype' => $requestresponsetype, 'projectmembers' => $projectmembers, 'categories' => $categories, 'query' => $query]);
I don't understand your idea clearly, but I guess something like:
$requests = DataRequest::where(function($q) {
$q->where("subject", "LIKE", "%$query%")
->orWhere("details", "LIKE", "%$query%")
->orWhere("id","LIKE","%$query%");
})
->where('status', '=', $status)
->paginate(10);
In my project, I created a scope to search, it's reuseable and readable.
//BaseModel
public function scopeSearch($query, $search, $fields)
{
$query->where(function($q) use ($search, $fields) {
foreach ($fields as $field) {
$q->orWhere($field, "LIKE", "%$search%");
}
}
}
$requests = DataRequest::search($query, ["subject", "details", "id"])
->where('status', '=', $status)
->paginate(10);

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

Can't upload file to server Laravel

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've got an error
Unable to create the "/uploads/products/" directory
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', 'files' => true, '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::textarea('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('Add', array('class'=>'btn btn-large btn-primary btn-block'))}}
{{ Form::close() }}
Update
Current bootstrap/paths.php file:
return array(
'app' => __DIR__.'/../app',
'public' => __DIR__.'/../public',
'base' => __DIR__.'/..',
'storage' => __DIR__.'/../app/storage',
);
Sounds like the public/uploads/products folder does not exist, and Laravel does not have permission to create it.
Try create the folder manually, make sure Laravel has writable access to it by running chmod 775 public/uploads/products . Then try the code again.

Categories