'PHP - Laravel is not storing files from request although the response is 200
Trying to upload a photo locally using Laravel with Vuejs
- I am sending the file from the Vue component to the backend like the code below:
<div class="form-group">
<label for="photo">photo</label>
<input
type="file"
class="form-control"
id="photo"
name="photo"
ref="inputFile"
/>
<hr />
</div>
<button
type="submit"
class="btn btn-primary">
Add
</button>
</form>
and this is the script in the same component
import { mapActions } from "vuex";
export default {
data() {
return {
category: {
photo: this.$refs.inputFile,
csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
config: {
headers: { 'content-type': 'multipart/form-data' }
}
},
};
},
methods: {
...mapActions(["createCategory"]),
submitForm() {
const form_data = new FormData();
form_data.append('photo', this.category.photo);
form_data.append('csrf', this.category.csrf);
// The following method is the mapped action
this.createCategory(form_data);
}
},
};
</script>
The mutations.js file
createCategory(state, category) {
axios.post('http://127.0.0.1:8000/api/categories', category).then(res => {
console.log("Response: " + res);
}).catch(res => {
console.log("Exp: " + res);
});
}
The actions.js file
createCategory(context, category) {
context.commit('createCategory', category);
}
- At the backend I am using categories driver in > filesystems.php as the following:
'categories' => [
'driver' => 'local',
'root' => base_path() . '/images/categories',
'url' => env('APP_URL').'/public',
'visibility' => 'public',
],
- uploading the file using $request->photo->store method as the code in the following Controller
public function store(CategoryRequest $request) {
try {
// Start Uploading File
$file = "";
if($request->has('photo')) {
$file = $request->photo;
$folder = 'categories';
$file->store('/', $folder);
$filename = $file->hashName();
$path = 'images/' . $folder . '/' . $filename;
}
// End Uploading File
// Start creating category
$category = new Category();
$category->photo = $path;
$category->save();
// End creating category
return response()->json(['message' => 'Created Successfully'], 200);
} catch(\Exception $ex) {
return $ex;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
