John Davidson

php - move_uploaded_file is not fetching path in laravel

0 comments
Message:


Here is my controller


    public function createAdmin()
{

$photo=$_FILES['bannerPic']['name'];
$tempname=$_FILES['bannerPic']['tmp_name'];

// echo $tempname." ".$photo;
move_uploaded_file($tempname, 'picture/banner/'.$photo);

$data=[
'sliderPic' => $photo,
];

dd($data);
// \App\Models\Banner::create($data);
// return view('Banner');
}

here is my route


    Route::post('/BannerEdit', [App\Http\Controllers\BannerController::class, 
'createAdmin']);

here is my blade form


    <form action="{{ url('') }}/BannerEdit" method="post" class="col-12" 
enctype="multipart/form-data">
@csrf

<div class="mb-3 col-12">
<label class="col-4 text-label form-label">Banner Photo*</label>
<input type="file" name="bannerPic" class="form-control input-rounded col-4 mb-3"
required>
</div>
<div class="mb-3 text-end">
<input type="submit" class="btn btn-primary" value="Upload">
</div>
</form>

When i submit the data it Gives me an Error as


move_uploaded_file(picture/banner/favicon.jpg): Failed to open stream: No such file or directory


But this Directory Exists


And i checked with full pathof localhost then it does not supports http path



My Answer:
In Laravel, you should use the `request()` method to access uploaded files instead of `$_FILES`. Here is an example of how you can modify your controller to properly handle file uploads in Laravel:

php
public function createAdmin(Request $request)
{
if ($request->hasFile('bannerPic')) {
$photo = $request->file('bannerPic');
$filename = $photo->getClientOriginalName();
$photo->move(public_path('uploads'), $filename);

// You can also store the file path in the database if needed
$filePath = 'uploads/' . $filename;

// Do something with the file path
// return response()->json(['message' => 'File uploaded successfully', 'path' => $filePath]);
} else {
// Handle the case where no file was uploaded
// return response()->json(['message' => 'No file uploaded']);
}
}


In this example, we are using the `Request` class to access the uploaded file. We check if a file was uploaded using the `hasFile()` method and then retrieve the file using the `file()` method. We then move the file to the `public/uploads` directory using the `move()` method.

Make sure to update the file upload path and any other logic as needed for your application.

Rate this post

3 of 5 based on 9376 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us