Laravel - Array Strings and Texts does not store in my database - php

I am new to laravel so please guide me, My problem is, I need to store a string and text array in my database in laravel, tho I cannot pass anything inside the database using arrays.. can anyone help me out here please thanks.
Here is my code in View and Controller
My code in View
{!! Form::open(['action'=>'Admin\AboutusController#store', 'method' => 'POST','enctype'=>'multipart/form-data', 'name' => 'add_name', 'id' => 'add_name']) !!}
<div class="form-group">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td> {{Form::text('title[]', '', ['class' => 'form-control', 'placeholder' => 'Enter a Title'])}}<br>
{{Form::textarea('description[]', '', ['class' => 'form-control', 'placeholder' => 'Enter a Description'])}} <br>
{{ Form::file('about_image[]') }}
</td>
<td>{{ Form::button('', ['class' => 'btn btn-success fa fa-plus-circle', 'id'=>'add','name'=>'add', 'style'=>'font-size:15px;']) }}</td>
</tr>
</table>
{{Form::submit('submit', ['class'=>'btn btn-primary', 'name'=>'submit'])}}
</div>
</div>
{!! Form::close() !!}
There you can see my textbox, textarea and submit button
My Controller
$this->validate($request, [
'title' => 'required',
'description' => 'required',
'about_image' => 'required'
]);
if ($request->has('about_image'))
{
//Handle File Upload
$about = [];
foreach ($request->file('about_image') as $key => $file)
{
// Get FileName
$filenameWithExt = $file->getClientOriginalName();
//Get just filename
$filename = pathinfo( $filenameWithExt, PATHINFO_FILENAME);
//Get just extension
$extension = $file->getClientOriginalExtension();
//Filename to Store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->storeAs('public/about_images',$fileNameToStore);
array_push($about, $fileNameToStore);
}
$fileNameToStore = serialize($about);
}
else
{
$fileNameToStore='noimage.jpg';
}
foreach ($about as $key => $value) {
$aboutContent = new About;
$aboutContent->title = $value->input('title');
$aboutContent->description = $value->input('description');
$aboutContent->about_image = $value;
$aboutContent->save();
}

You are trying to get information that is not available from the $about array.
try replacing it with:
foreach ($about as $key => $value) {
$aboutContent = new About;
$aboutContent->title = $request->title[$key];
$aboutContent->description = $request->description[$key];
$aboutContent->about_image = $value;
$aboutContent->save();
}
You might just want to make sure that the title and description line up with the correct image

Related

Laravel - Update Uploaded Files in Input File

I want to update my uploaded images, but as soon as I update 1 image the other images are removed why is that? I want to left them as what they are when they had been upload. help me please thanks.
Here is an image of the problem
Controller
Update, public function, here is where I put the logic of the code
public function update(Request $request, $id)
{
$this->validate($request, [
'title' => 'required',
'description' => 'required',
'fleet_image.*' => 'image|nullable|max:1999'
]);
$fleet = [];
if ($request->has('fleet_image'))
{
//Handle File Upload
foreach ($request->file('fleet_image') as $key => $file)
{
// Get FileName
$filenameWithExt = $file->getClientOriginalName();
//Get just filename
$filename = pathinfo( $filenameWithExt, PATHINFO_FILENAME);
//Get just extension
$extension = $file->getClientOriginalExtension();
//Filename to Store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->storeAs('public/fleet_images',$fileNameToStore);
array_push($fleet, $fileNameToStore);
}
$fileNameToStore = serialize($fleet);
}
else
{
$fileNameToStore='noimage.jpg';
}
if (count($fleet)) {
foreach ($fleet as $key => $value) {
$fleetContent = Fleet::find($id);
$fleetContent->title = $request->title[$key];
$fleetContent->description = $request->description[$key];
$implodedFleet = implode(' , ', $fleet);
if($request->hasFile('fleet_image')){
$fleetContent->fleet_image = $implodedFleet;
}
$fleetContent->save();
return redirect('/admin/airlineplus/fleets')->with('success', 'Content Updated');
}
}
return redirect('/admin/airlineplus/promotions')->with('success', 'Content Updated');
}
View, edit.blade.php
{!! Form::open(['action'=>['Admin\FleetsController#update',$fleet->id], 'method' => 'POST','enctype'=>'multipart/form-data', 'name' => 'add_name', 'id' => 'add_name']) !!}
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td> {{Form::text('title[]', $fleet->title, ['class' => 'form-control', 'placeholder' => 'Enter a Title', 'id'=>"exampleFormControlFile1"])}}<br>
{{Form::textarea('description[]', $fleet->description, ['class' => 'form-control', 'placeholder' => 'Enter a Description'])}} <br>
<div class="card card-body col-md-8">
#foreach(explode(' , ' ,$fleet->fleet_image) as $content)
<img src="{{ asset('storage/fleet_images/' . $content) }}" style="width:50px;height:50px;"><br/>
{{ Form::file('fleet_image[]',['id'=>'exampleFormControlFile1']) }}<br/>
#endforeach
</div>
</td>
</tr>
</table>
{{Form::hidden('_method', 'PUT')}}
{{Form::submit('submit', ['class'=>'btn btn-primary', 'name'=>'submit'])}}
</div>
{!! Form::close() !!}
On your Controller
$fleet = array();
$fleetContent = Fleet::find($id);
if ($request->has('fleet_image')) {
for($i=0;$i<3;$i++){
if(isset($request->file('fleet_image')[$i])){
$filenameWithExt = $request->file('fleet_image')[$i]->getClientOriginalName();
//Get just filename
$filename = pathinfo( $filenameWithExt, PATHINFO_FILENAME);
//Get just extension
$extension = $request->file('fleet_image')[$i]->getClientOriginalExtension();
//Filename to Store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $request->file('fleet_image')[$i]->move('public/fleet_images',$fileNameToStore);
array_push($fleet, $fileNameToStore);
}else{
$fleetContentExplode = explode(',',$fleetContent->fleet_image);
array_push($fleet,$fleetContentExplode[$i]);
}
}
}
On your View File
{!! Form::open(['action'=>['Admin\FleetsController#update',$fleet->id], 'method' => 'POST','enctype'=>'multipart/form-data', 'name' => 'add_name', 'id' => 'add_name']) !!}
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td> {{Form::text('title', $fleet->title, ['class' => 'form-control', 'placeholder' => 'Enter a Title', 'id'=>"exampleFormControlFile1"])}}<br>
{{Form::textarea('description', $fleet->description, ['class' => 'form-control', 'placeholder' => 'Enter a Description'])}} <br>
<div class="card card-body col-md-8">
#foreach(explode(' , ' ,$fleet->fleet_image) as $content)
<img src="{{ asset('storage/fleet_images/' . $content) }}" style="width:50px;height:50px;"><br/>
{{ Form::file('fleet_image[]',['id'=>'exampleFormControlFile1']) }}<br/>
#endforeach
</div>
</td>
</tr>
</table>
{{Form::hidden('_method', 'PUT')}}
{{Form::submit('submit', ['class'=>'btn btn-primary', 'name'=>'submit'])}}
</div>
{!! Form::close() !!}
NB:: I have just remove the array from your view input text

laravel 5.2 | upload file - Call to a member function getClientOriginalName() on null

i tried to upload profile picture pict but i got error "Call to a member function getClientOriginalName() on null"
this is my method :
$data = $request->input('fotodosen');
$photo = $request->file('fotodosen')->getClientOriginalName();
$destination = base_path() . '/public/uploads';
$request->file('fotodosen')->move($destination, $photo);
$data['fotodosen'] = $photo;
Dosen::create($data);
create :
{!! Form::open(array('fotodosen'=>'create', 'method'=>'POST', 'files'=>true, 'url'=>'uploads')) !!}
{!! Form::file('image') !!}
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
<i class="fa fa-btn fa-user"></i> Register
</button>
{!! Form::close() !!}
already edit method to :
$photo = $request->file('fotodosen')->getClientOriginalName($photo);
still got that error. what am i missing?
UPDATE :
public function store(CreateDosenRequest $request)
{
$user = User::create([
'name' => $request->input('name'),
'username' => $request->input('username'),
'email' => $request->input('email'),
'password' => $request->input('password'),
'admin' => $request->input('admin'),
]);
$dosen = Dosen::create([
'iddosen' => $request->input('iddosen'),
'nipy' => $request->input('nipy'),
'namadosen' => $user->name,
'user_id' => $user->id,
'alamatdosen' => $request->input('alamatdosen'),
'notelpdosen' => $request->input('notelpdosen'),
'tempatlahirdosen' => $request->input('tempatlahirdosen'),
'tanggallahirdosen' => $request->input('tanggallahirdosen'),
'agamadosen' => $request->input('agamadosen'),
]);
if ($request->hasFile('image')) {
$data = $request->input('image');
$photo = $request->file('image')->getClientOriginalName();
$destination = public_path() . '/uploads/';
$request->file('image')->move($destination, $photo);
$data['fotodosen'] = $photo;
Dosen::create($data);
}
You have the file name as image try to use image instead of fotodosen
$photo = $request->file('image')->getClientOriginalName();
Full code
$data = $request->input('image');
$photo = $request->file('image')->getClientOriginalName();
$destination = base_path() . '/public/uploads';
$request->file('image')->move($destination, $photo);
You can check for the file like,
if ($request->hasFile('image')) {
// your code here
}
From Http Requests and an article file upload in laravel 5
I had the same issue so I solved it using html form attribute enctype="multipart/form-data"
Example
<form name="le_form" action="/ft" method="POST" enctype="multipart/form-data">
For more information see
http://php.net/manual/en/features.file-upload.post-method.php
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/enctype
For me, what I found out is that i did not included the enctype'=>'multipart/form-data on the form. When i did, it eventually solved the problem.
just do this if you are uploading a file or have a file field inside your form
{{ Form::open(array('url' => 'dashboard/new_job', 'enctype'=>'multipart/form-data')) }}
OR
<form action="/ft" method="POST" enctype="multipart/form-data">

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

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