laravel5 controller issue. Undefined variable: filename - laravel

I want to upload a blogger's profile image but I get an error:
Undefined variable: file_name.
I think it is a controller issue. I don't know why the variable is not defined, though I declared the same variable name.
I restarted the server but it did not work.
So please help me out.
BloggerController.php
public function store(Request $request, User $user_id)
{
$user_id = DB::table('users')->where('id', $user_id)->get();
if ($request->hasfile('image')) {
$file = $request->file('image');
$ext = $file->getClientOriginalExtension();
$file_name = time() . '.' . $ext;
$file->move('bloggers/', $file_name);
}
$blog = Blog::create(
['user_id' => $user_id],
[
'image' => $file_name,
'introduction' => $request->introduction,
]
);
return redirect(route('blogger'));
}
I also changed the store method.
if ($request->hasfile('image')) {
$file_name = $request->file('image')->getClientOriginalName();
$request->file('image')->storeAs('bloggers/', $file_name);
}
My migration
Schema::create('blogs', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('bloggers');
$table->string('image');
$table->string('introduction');
$table->timestamps();
});

To be sure that your variable $fillename is available then change your code to this
if($request->hasfile('image')){
$file = $request->file('image');
$ext = $file->getClientOriginalExtension();
$filename = time().'.'.$ext;
$file->move('bloggers/', $filename);
$blog = Blog::create(
['user_id' => $user_id],
[
'image'=>$filename,
'introduction' => $request->introduction,
]
);
}

you must return file address and name in uploader
public function store(Request $request, User $user_id){
$user_id = DB::table('users')->where('id', $user_id)->get();
if($request->hasfile('image')){
$file = $request->file('image');
$ext = $file->getClientOriginalExtension();
$file_name = time().'.'.$ext;
$file->move('bloggers/', $file_name);
}
$blog = Blog::create(
['user_id' => $user_id],
[
'image'=>"/bloggers/".$file_name,
'introduction' => $request->introduction,
]
);
return redirect(route('blogger'));
}
i think its work

You tried accessing the variable out of scope. Make it an external variable by declaring it out of the if function as I show below on line 2 of the code.
...
public function store(Request $request, User $user_id){
$file_name="";
$user_id = DB::table('users')->where('id', $user_id)->get();
if($request->hasfile('image')){
$file = $request->file('image');
$ext = $file->getClientOriginalExtension();
$file_name = time().'.'.$ext;
$file->move('bloggers/', $file_name);
}
$blog = Blog::create(
['user_id' => $user_id],
[
'image'=>"/bloggers/".$file_name,
'introduction' => $request->introduction,
]
);
return redirect(route('blogger'));
}
...

Related

Updating User Profile in Laravel

Hello I've been trying to update the avatar profile of a user, through image intervention, tho I cannot seem to update it. The $user->save isn't being read by Laravel
public function update_avatar(Request $request) {
if($request->hasFile('avatar')) {
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300, 300)->save( public_path('/images/avatars/' . $filename) );
$user = Auth::user();
$user->avatar = $filename;
$user->update();
}
Auth::user() is not your model. Please try:
$user = User::query()
->whereId(auth()->user()->id)
->update([
'avatar' => $filename
]);

RESOLVED Laravel 8 Update image and delete old image

I need help with a little thing.
I have a product table with an image:
Here is my function store which works perfectly
$fileName = null;
if (request()->hasFile('image')) {
$image = request()->file('image');
$fileName = md5($image->getClientOriginalName() . time()) . "." . $image->getClientOriginalExtension();
$image->move('./img/', $fileName);
}
Product::create([
'title' => $request->input('title'),
'subtitle' => $request->input('subtitle'),
'description' => $request->input('description'),
'price' => $request->input('price'),
'image' => $fileName,
]);
I am trying to modify the image in update but I do not know how to do it and I am in difficulty currently
Here is my update function where the image is missing to modify it and delete the old one
public function update(Request $request, Product $product)
{
$product->title = $request->input('title');
$product->subtitle = $request->input('subtitle');
$product->description = $request->input('description');
$product->price = $request->input('price');
$product->save();
Thanks
You can modify your update function like this
public function update(Request $request, Product $product)
{
$fileName = null;
$currentImage = $product->image;
if (request()->hasFile('image')) {
$image = request()->file('image');
$fileName = md5($image->getClientOriginalName() . time()) . "." . $image->getClientOriginalExtension();
$image->move('./img/', $fileName);
}
else
$fileName = $currentImage
if($fileName && $currentImage)
{
// Delete the old file i.e $fileName
}
$product->title = $request->input('title');
$product->subtitle = $request->input('subtitle');
$product->description = $request->input('description');
$product->price = $request->input('price');
$product->image = $fileName;
$product->save();
}
It's good with this :
$fileName = null;
$currentImage = $product->image;
if (request()->hasFile('image')) {
$image = request()->file('image');
$fileName = md5($image->getClientOriginalName() . time()) . "." . $image->getClientOriginalExtension();
$image->move('./img/', $fileName);
}
else
$fileName = $currentImage;
if($fileName && $currentImage)
{
Storage::delete('./img/' . $currentImage);
}
Thanks

Laravel: How to return JSON response when using foreach

I am uploading images using Vue and my Laravel backend endpoint looks like this below. I am unsure of what to put in the response though since it is a foreach that iterates through each file and uploads them but I still want to return the response as JSON.
public function upload(Request $request)
{
$files = $request->file('images');
foreach ($files as $file) {
Storage::put('store/assets/', file_get_contents($file->getRealPath()), ['visibility' => 'public']);
}
return response()->json(????);
}
public function upload(Request $request)
{
$files = $request->file('images');
$stack = [];
foreach ($files as $file) {
$fileName = Storage::put('store/assets/', file_get_contents($file->getRealPath()),
['visibility' => 'public']);
array_push($stack, $fileName);
}
return response()->json($stack);
}
Or you can just do like that:
$data = ["success" => 1];
return response()->json($data);
My offer:
if your query is executed succesfully
$data=[
"stat"=>1,
"data"=>[
"first"=>1,
...
]
]
else
$data=[
"stat"=>0,
"error"=>"Not successfull"
]

Laravel-api for multiple file upload

I want to make laravel api for multiple file upload when i am uploading then its gives error $data is undefined variable.please help me how to remove this error..?
FileUploadController.php
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use App\Detail;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Auth;
class FileUploadController extends Controller
{
public function uploadFile(Request $request){
$this->validate($request, [
'user_sharing_image' => 'required',
'user_sharing_image.*' => 'mimes:doc,pdf,docx,zip'
]);
if($request->hasfile('user_sharing_image'))
{
foreach($request->file('user_sharing_image') as $file)
{
$name=$file->getClientOriginalName();
$file->move(public_path().'/files/', $name);
$data[] = $name;
}
}
$file= new Detail();
$file->title = $request->title;
$file->info = $request->info;
$file->user_id = $request->user()->id;
$file->user_sharing_image=json_encode($data);
$file->save();
return back()->with('success', 'Data Your files has been successfully added');
}
}
I am using laravel passport for auth and want to store user_id but do not geting please help me how to resolve both problem from this code
Give it a try
$data = [];
if($request->hasfile('user_sharing_image'))
{
foreach($request->file('user_sharing_image') as $key=>$file)
{
$name=$file->getClientOriginalName();
$file->move(public_path().'/files/', $name);
$data[$key] = $name;
}
}
$file= new Detail();
$file->title = $request->title;
$file->info = $request->info;
$file->user_id = Auth::user()->id;
$file->user_sharing_image=json_encode($data);
$file->save();
You are getting this error because $data is not defined.
Before foreach loop you can declare it as $data = array();
i think you should use files method to return array of files :
foreach($request->files('user_sharing_image') as $file)
Hello fellow developers
This will work properly
$files = $request->allFiles('imgs');
foreach ($files as $key => $img) {
# code...
$filename = request()->getSchemeAndHttpHost() . '/assets/images/users/upload/profile/photos/' . time() . '.'. $img->extension();
$img->move(public_path('/assets/images/users/upload/profile/photos/'), $filename);
$photos = UserPhoto::create([
'user_id' => $user->id,
'name' => $filename
]);
}
return response()->json([
'status' => true,
'data' => 'Photos Uploaded Successfully!!'
]);

laravel 5 Call to undefined method Illuminate\Database\Query\Builder::posts()

i want to store this information but that doesn't work i still have this error "Call to undefined method Illuminate\Database\Query\Builder::posts()
"
public function store(Request $request)
{
$this->validate($request,[
'title'=>'required',
'slug'=>'required',
'excerpt'=>'required',
'body'=>'required',
'created_at'=>'date_format:Y-m-d H:i:s',
'team_id'=>'required',
'image'=>'mimes:jpg,jpeg,png,bmp',
]);
$data = $this->handleRequest($request);
$request->user()->posts()->create($data);
return redirect('/backend/blog')->with('message', 'Your post was created successfully!');
}
private function handleRequest($request)
{
$data = $request->all();
if ($request->hasFile('image'))
{
$image = $request->file('image');
$fileName = $image->getClientOriginalName();
$destination = $this->uploadPath;
$image->move($destination, $fileName);
$data['image'] = $fileName;
}
return $data;
}

Resources