Laravel更改配置文件API给出空值

时间:2019-03-02 06:29:17

标签: laravel-5.7

我正在laravel中创建更改个人资料图片api。我想更新用户表中的个人资料图片,但不想插入或更新我的图片。贝娄是我的代码,请帮助我如何更新用户表。

fileUploadController.php

<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use App\Detail;
use App\Profile;
use Illuminate\Support\Facades\DB;
use Session;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Auth;

class FileUploadController extends Controller
{

     public function changeProfile(Request $request,$id){

        $this->validate($request, [

            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',

        ]);

         $updateuser = User::find($id);


         if($file = $request->hasFile('image')) {

            $file = $request->file('image');

            $fileName = $file->getClientOriginalName() ;
            $destinationPath = public_path().'/files/' ;
            $file->move($destinationPath,$fileName);
            $updateuser->image = '/files/'.$fileName;
        }

        $updateuser->save();
        return $updateuser;

     }

}

2 个答案:

答案 0 :(得分:1)

public function changeProfile(Request $request,$id){

    $this->validate($request, [

        'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',

    ]);

     $updateuser = User::find($id);
    if($request->hasFile('image'))
    {
        $filewithext = $request->file('image')->getClientOriginalName();
        $ext = $request->file('image')->getClientOriginalExtension();
        $fileToStrore = $filewithext;
        $path = $request->file('image')->storeAs('public/files',$fileToStrore);
        $updateuser->image = $fileToStrore;
    }


    $updateuser->save();
    return $updateuser;

 }

此代码对我有用。我希望它也对您有用... 祝你好运。

答案 1 :(得分:0)

此代码为我工作.....

fileUploadController.php      公共功能changeProfile(Request $ request,$ id){

         $updateuser = User::find($id);

        if ($request->hasFile('image')) {
               $images = $request->file('image');
               $destinationPath = public_path('files');
               $imageName = time().'.'.$images->getClientOriginalExtension();
               $images->move($destinationPath, $imageName); 
               $updateuser->image= $imageName;
            }else{
              $updateuser->image= '';
            }

      $updateuser->update();

       return ['message' => 'Image Uploaded Successfully'];
     }