Call to a member function getClientOriginalName() on null when upload image use file system Laravel - laravel

I want to upload an image using Laravel storage file system in my admin data. However, there's an error when I attempt to upload an image.
Call to a member function getClientOriginalName() on null
Controller
public function store(Request $request)
{
$admin = $request->all();
$fileName = $request->file('foto')->getClientOriginalName();
$destinationPath = 'images/';
$proses = $request->file('foto')->move($destinationPath, $fileName);
if($request->hasFile('foto'))
{
$obj = array (
'foto' => $fileName,
'nama_admin' => $admin['nama_admin'],
'email' => $admin['email'],
'jabatan' => $admin['jabatan'],
'password' => $admin['password'],
'confirm_password' => $admin['confirm_password']
);
DB::table('admins')->insert($obj);
}
return redirect()->route('admin-index');
}
View
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
Error

You can check wheather you are getting file or not by var_dump($request->file('foto')->getClientOriginalName());
And make sure your form has enctype="multipart/form-data" set
<form enctype="multipart/form-data" method="post" action="{{ url('/store')}}">
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
</form>

Error because of client Side
<form enctype="multipart/form-data" method="post" action="{{ url('/store')}}">
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
</form>
you ned to add enctype="multipart/form-data" inside the form
If You are using the form builder version
{!! Form::open(['url' => ['store'],'autocomplete' => 'off','files' => 'true','enctype'=>'multipart/form-data' ]) !!}
{!! Form::close() !!}
Then In your Controller You can check if the request has the file
I have Created the simple handy function to upload the file
Open Your Controller And Paste the code below
private function uploadFile($fileName = '', $destinationPath = '')
{
$fileOriginalName = $fileName->getClientOriginalName();
$timeStringFile = md5(time() . mt_rand(1, 10)) . $fileOriginalName;
$fileName->move($destinationPath, $timeStringFile);
return $timeStringFile;
}
And the store method
Eloquent way
public function store(Request $request)
{
$destinationPath = public_path().'images/';
$fotoFile='';
if ($request->hasFile('foto'))
{
$fotoFile= $this->uploadFile($request->foto,$destinationPath );
}
Admin::create(array_merge($request->all() , ['foto' => $fotoFile]));
return redirect()->route('admin-index')->with('success','Admin Created Successfully');
}
DB Facade Version
if You are using DB use use Illuminate\Support\Facades\DB; in top of your Controller
public function store(Request $request)
{
$admin = $request->all();
$destinationPath = public_path().'images/';
$fotoFile='';
if ($request->hasFile('foto'))
{
$fotoFile = $this->uploadFile($request->foto,$destinationPath );
}
$obj = array (
'foto' => $fotoFile,
'nama_admin' => $admin['nama_admin'],
'email' => $admin['email'],
'jabatan' => $admin['jabatan'],
'password' => $admin['password'],
'confirm_password' => $admin['confirm_password']
);
DB::table('admins')->insert($obj);
return redirect()->route('admin-index');
}
Hope it is clear

Related

Laravel 9 Vue js 3 multipart form, console showing full html, not only the retrieved data

I'm using a multipart form to send texts and image to database,
The data have been successfully sent to the database, but why in the console it is showing the data infull html ? not only the data that has been retrieved ?
this is my code
<template>
<div class="gabungPage">
<div class="row">
<div class="backgroundGabung" id="hrefGabung">
<div class="tulisanGabung p-5">
<div class="cardGabung">
<p class="teksGabung">Tingkatkan bisnismu sekarang dengan bergabung menjadi mitra JAI'</p>
<form #submit.prevent="submitForm">
<div class="form-group">
<label for="nama">Nama</label>
<input
type="text"
id="nama"
v-model="formulirs.nama"
class="form-control"
/>
</div>
<div class="form-group">
<label for="alamat">Alamat</label>
<input
type="text"
id="alamat"
v-model="formulirs.alamat"
class="form-control"
/>
</div>
<div class="form-group">
<label for="email">Email</label>
<input
type="text"
id="email"
v-model="formulirs.email"
class="form-control"
/>
</div>
<div class="form-group">
<label for="nomor">nomor</label>
<input
type="text"
id="nomor"
v-model="formulirs.nomor"
class="form-control"
/>
</div>
<div class="form-group">
<label for="image">Image</label>
<input
type="file"
id="image"
ref="imageInput"
#change="uploadImage"
/>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
<div class="tesss">
<h1> <span class="tulisKiri1">Gabung jadi</span> <br> <span class="tulisKiri2">mitra jahit</span></h1>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
formulirs: {
nama: '',
alamat: '',
nomor: '',
email: '',
image: null,
},
};
},
methods: {
uploadImage() {
this.formulirs.image = this.$refs.imageInput.files[0];
},
async submitForm() {
const formData = new FormData();
formData.append('nama', this.formulirs.nama);
formData.append('alamat', this.formulirs.alamat);
formData.append('email', this.formulirs.email);
formData.append('nomor', this.formulirs.nomor);
formData.append('image', this.formulirs.image);
axios.post('/api/submit-form', formData).then(
response => {
console.log(response);
this.$toast.success(`Data berhasil dikirim`,{
position: "bottom",
});
}
). catch(error => {
console.log('error');
this.$toast.error(`Terjadi kegagalan`,{
position: "bottom",
});
})
},
},
};
</script>
the routes/web.php
Route::post('/api/submit-form', [FormulirsController::class, 'store']);
the controller
public function store(Request $request)
{
$validatedData = $request->validate([
'nama' => 'required',
'alamat' => 'required',
'nomor' => 'required',
'email' => 'required|email',
'image' => 'required|image',
]);
$formulir = new Formulirs;
$formulir->nama = $validatedData['nama'];
$formulir->alamat = $validatedData['alamat'];
$formulir->nomor = $validatedData['nomor'];
$formulir->email = $validatedData['email'];
$image = $request->file('image');
$imageName = time().$image->getClientOriginalName();
$image->storeAs('public/images', $imageName);
$formulir->image = $imageName;
$formulir->save();
return back()->with('success', 'Data berhasil dikirim');
}
I have tried to show the data only by changing to
console.log(response.data)
But it got worse, it only shows full html page in the console, what should I do so that it doesn't display the full html page?
You're making an axios request and returning back method. This is used for redirecting in a monolitic app. I recommend you return a JSON response in your controller. Something like this:
public function store(Request $request)
{
$validatedData = $request->validate([
'nama' => 'required',
'alamat' => 'required',
'nomor' => 'required',
'email' => 'required|email',
'image' => 'required|image',
]);
$formulir = new Formulirs;
$formulir->nama = $validatedData['nama'];
$formulir->alamat = $validatedData['alamat'];
$formulir->nomor = $validatedData['nomor'];
$formulir->email = $validatedData['email'];
$image = $request->file('image');
$imageName = time().$image->getClientOriginalName();
$image->storeAs('public/images', $imageName);
$formulir->image = $imageName;
$formulir->save();
return back()->with('success', 'Data berhasil dikirim'); // this is yours
return response()->json('Data berhasil dikirim'); // 200 status code is the second param by default. You can change for whatever you want.
}

Laravel 9 how to pass parameter in url from one controller to another controller?

I was facing this problem of missing parameter when trying to pass a parameter from one controller to another controller. The parameter is $id whereby the data is originally from post method in details blade.php into function postCreateStepOne However, I want to pass the data into a new view and I return
redirect()->route('details.tenant.step.two')->with( ['id' => $id]
);}
And this is where error occur. However, it works fine if I skip it into a new route and directly return into a view with the compact parameter. For Example,
return view('document.details-step-two', compact('id', 'property'));
However, I would prefer a new url as I was doing multistep form using Laravel.
Error
web.php
Route::get('/document/details/viewing/{id}', 'ViewDetails')->name('details.tenant');
Route::post('/document/details/viewing/{id}', 'postCreateStepOne')->name('post.step-one');
Route::get('/document/details/viewing/step-2/{id}', 'ViewDetailsStep2')->name('details.tenant.step.two');
TenanatController.php
public function viewDetails($id){
$view = Properties::findOrFail($id);
return view('document.details', compact('view'));
}
public function ViewDetailsStep2(Request $request, $id){
$view = Properties::findOrFail($id);
$property = $request->session()->get('property');
return view('document.details-step-two', compact('view', 'property'));
}
public function postCreateStepOne($id, Request $request)
{
$validatedData = $request->validate([
'property-name' => 'required',
]);
if(empty($request->session()->get('property'))){
$property = new Tenancy();
$property->fill($validatedData);
$request->session()->put('property', $property);
}else{
$property = $request->session()->get('property');
$property->fill($validatedData);
$request->session()->put('property', $property);
}
return redirect()->route('details.tenant.step.two')->with( ['id' => $id] );
}
details.blade.php
<form action="{{ route('post.step-one', $view->id) }}" method="POST">
#csrf
<div class="card-body">
<div class="form-group">
<label for="title">Property Name:</label>
<input type="text" value="" class="form-control" id="property-name" name="property-name">
</div>
</div>
<div class="card-footer text-right">
<button type="submit" class="btn btn-primary">Next</button>
</div>
</form>
When you use with on a redirect the parameter is passed through the session. If you want to redirect to a route with a given route parameter you should pass that parameter in the route function itself like e.g.
return redirect()->route('details.tenant.step.two', ['id' => $id]);

Laravel stored image is tmp not jpg when update data

When I update image the data stored is tmp, not an image file.
Here's my controller:
public function update(Request $request, $id)
{
$change = Post::findorfail($id);
$before = $change->image;
$post = [
'title' => $request['title'],
'tags_id' => $request['tags_id'],
'content' => $request['content'],
'image' => $before,
];
if($request->hasFile('image')){
$request->image->move(public_path().'/image', $before);
}
$change->update($post);
return redirect('post');
}
View:
<div class="form-group row mb-4">
<label class="col-form-label text-md-right col-12 col-md-3 col-lg-3">Featured Image</label>
<div class="col-sm-12 col-md-7">
<input type="file" name="image" class="form-control" value="{{ $data->image }}">
</div>
</div>
Thanks for your help
You must save request image file into system instead of moving old image file.
public function update(Request $request, $id)
{
$change = Post::findorfail($id);
$image = $request->hasFile('image')
? $request->photo->store('image', 'public')
: $change->image;
$post = [
'title' => $request['title'],
'tags_id' => $request['tags_id'],
'content' => $request['content'],
'image' => '/storage/' . $image,
];
$change->update($post);
return redirect('post');
}
This will save new image into /storage/public/image/ path. To make this address accessible through url, you must create a symlink from public path to storage path by running this:
php artisan storage:link
This will create a storage symlink in /public folder which points to /storage/public path. Read the complete documentation about this functionality here: https://laravel.com/docs/8.x/filesystem#the-public-disk

Field 'album_id' doesn't have a default value

I want to create a photo album using laravel version 8.9.0
I have created an album, when I click on an album I will go to the gallery view, when I upload a photo an error occurs like this
General error: 1364 Field 'album_id' doesn't have a default value (SQL: insert into galeris (deskripsi, user_id, image, updated_at, created_at) values (asa, 1, 1604133200.png, 2020-10-31 08:33:20, 2020-10-31 08:33:20))
create_galeris_table.php
public function up()
{
Schema::create('galeris', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->integer('user_id');
$table->integer('album_id')->unsigned();
$table->string('image');
$table->text('deskripsi');
$table->foreign('album_id')->references('id')->on('albums')->onDelete('CASCADE')->onUpdate('CASCADE');
$table->timestamps();
});
}
GaleriController.php
public function store(Request $request)
{
$request->validate([
'deskripsi' => 'required',
'image' => 'required|image|mimes:jpg,jpeg,png|max:2000',
]);
$galeri = New Galeri;
$galeri->deskripsi = $request->deskripsi;
$galeri->user_id = auth()->id();
if ($request->hasFile('image')) {
$file = $request->file('image');
$fileName = time().'.'.$file->getClientOriginalExtension();
$destinationPath = public_path('images/galeri');
$file->move($destinationPath, $fileName);
$galeri->image = $fileName;
}
$galeri->save();
return back()->with(['success' => 'Data Berhasil Disimpan!']);
}
galeri.blade.php
<div class="modal fade" id="uploadImage" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<form action="{{route('galeri.store')}}" method="post" enctype="multipart/form-data">
#csrf
<div class="form-group">
<input type="file" name="image" class="form-control" style="padding-top: 3px;">
</div>
<div class="form-group">
<textarea name="deskripsi" class="form-control" placeholder="Deskripsi"></textarea>
</div>
<button type="submit" class="btn btn-success btn-block">Save</button>
</form>
</div>
</div>
</div>
</div>
Because in create_galeris_table.php migration file album_id field is not nullable or has a default value and in your GaleriController.php you are not inserting a value for album_id
So you could make album_id nullable in your migration file
$table->integer('album_id')->unsigned()->nullable();
Or insert a value for album_id while creating a new gallery record, so in store method you will add
public function store(Request $request)
{
$request->validate([
'deskripsi' => 'required',
'image' => 'required|image|mimes:jpg,jpeg,png|max:2000',
]);
$galeri = New Galeri;
$galeri->deskripsi = $request->deskripsi;
$galeri->user_id = auth()->id();
$album = Album::find('some-id'); // this id of the album you want to add to this gallery
$galeri->album_id = $album->id;
if ($request->hasFile('image')) {
$file = $request->file('image');
$fileName = time().'.'.$file->getClientOriginalExtension();
$destinationPath = public_path('images/galeri');
$file->move($destinationPath, $fileName);
$galeri->image = $fileName;
}
$galeri->save();
return back()->with(['success' => 'Data Berhasil Disimpan!']);
}

I Cannot able to pass the id in route file in laravel

I am declaring the above thing in the route for edit of my data.
Route::get('editproduct/{id}', 'HomeController#Edit_Product');
Above is my editproduct.blade.php page
<?php
$id = $_GET['eid'];
$product_info = DB::select("SELECT * FROM `product` WHERE `pid` = '".$id."'");
foreach($product_info as $detail)
{
$actual_image = 'theme/uploads/'.$detail->pimage;
$product_image = $detail->pimage;
$product_name = $detail->pname;
$product_price = $detail->pprice;
}
?>
#include('include/header')
<div class="tab-pane add-product-view" id="profile">
<form name="add_product" method="post" enctype="multipart/form-data" role="form" action="{{ url('edit-product-process') }}">
{{ csrf_field() }}
<div class="form-label">Add Image: </div>
<div class="form-field"><input type="file" name="add_image" id="add_image" value="{{asset($actual_image)}}" /></div>
<img src="{{asset($actual_image)}}" width="50" height="50" />
<div class="form-label">Product Name:</div>
<div class="form-field"><input type="text" name="product_name" id="product_name" value="{{ $product_name }}" /></div>
<div class="form-label">Product Price:</div>
<div class="form-field"><input type="text" name="product_price" id="product_price" value="{{ $product_price }}" /></div>
<div class="btn btn-primary"><input type="submit" name="submit" value="Add Product"</div>
</form>
</div>
#include('include/footer')
This is My HomeController.blade.php
public function Edit_Product($id){
return View::make('editproduct')->with('id', $id);
}
public function edit_product_process(Request $request){
$prd_id = $request->pid;
$imageTempName = $request->file('add_image')->getPathname();
$imageName = $request->file('add_image')->getClientOriginalName();
$path = base_path() . '/theme/uploads/';
$request->file('add_image')->move($path , $imageName);
$remember_token = $request->_token;
$date = date('Y-m-d H:i:s');
$pname = $request->product_name;
$pprice = $request->product_price;
DB::table('product')->where('pid',$prd_id)->update(
array(
'pimage' => $imageName,
'pname' => $pname,
'pprice' => $pprice,
'remember_token' => $remember_token,
'created_at' => $date,
'updated_at' => $date,
)
);
return redirect('dashboard');
}
I am getting the below error, Please anyone can be able to help me, I am new at laravel.
page is not found
NotFoundHttpException in RouteCollection.php line 161:
If you're getting this error when you're trying to submit the form, you should check you route. It should look like this:
Route::post('edit-product-process', 'HomeController#edit_product_process');
Also, to pass an ID into edit_product_process you need to add field with ID into the form:
<input type="hidden" name="id" value="{{ $id }}">
And then you can get it in edit_product_process with $request->id
Your route should be as:
Route::get('editproduct/{id}', 'HomeController#Edit_Product')->name('product.edit');
Then you can use it as:
{{ route('product.edit', ['id' => $id]) }}
But it's a terrible practice to use DB queries in views.
Please do read more about queries and controllers in the docs.
Check Your Controller Name Why r using blade in that.This is bad practice.HomeController.blade.php

Resources