简体   繁体   English

Laravel 5.2 用户注册时上传图片到上传文件夹

[英]Laravel 5.2 Upload Image to uploads folder while user registration

I am trying to save uploaded image to uploads folder as well as database at the time of user registration, the image name is successfully saved to the database along with user details like name, address, email and etc. I am new to laravel.我试图在用户注册时将上传的图像保存到上传文件夹和数据库中,图像名称与用户详细信息(如姓名、地址、电子邮件等)一起成功保存到数据库中。我是 laravel 的新手。 Please can any one suggest me, thank you.请哪位大神给我推荐一下,谢谢。

Please find below is my register.blade.php请在下面找到我的 register.blade.php

@extends('layouts.site')
@section('content')
<div class="login-content">
<a class="hiddenanchor" id="signup">
</a>
<a class="hiddenanchor" id="signin">
</a>
@include('layouts.site-navigation')
@include('errors.errors')
<div class="login_wrapper">
<div class="animate form login_form">
<section class="login_content">
<!-- <form> -->
<h1>Registration Form
</h1>
{!! Form::open(array('url' => URL_USERS_REGISTER, 'method' => 'POST', 
'name'=>'formLanguage ', 'novalidate'=>'', 'class'=>"loginform", 
'name'=>"registrationForm", 'files'=>'true')) !!}
 <div>
 </div>
 <div>
 {{ Form::text('username', $value = null , $attributes = 
 array('class'=>'form-control',
 'placeholder' => getPhrase("username"),
 'ng-model'=>'username',
 'required'=> 'true',
  'ng-class'=>'{"has-error": registrationForm.username.$touched && 
  registrationForm.username.$invalid}',
  'ng-minlength' => '4',
  )) }}
  </div>
  <div>
  {{ Form::text('rollnumber', $value = null , $attributes = 
  array('class'=>'form-control',
  'placeholder' => getPhrase("roll number"),
  'ng-minlength' => '2',
   )) }}
   <div>
   {{ Form::text('branch', $value = null , $attributes = 
   array('class'=>'form-control',
        'placeholder' => getPhrase("branch"),
        'ng-minlength' => '2',
        )) }}
      </div>
      <div>
        {{ Form::text('phone', $value = null , $attributes = 
    array('class'=>'form-control',
        'placeholder' => getPhrase("phone"),
        'ng-model'=>'phone',
        'ng-pattern' => getRegexPattern('phone'),
        'required'=> 'true',
        'ng-class'=>'{"has-error": registrationForm.phone.$touched && 
   registrationForm.phone.$invalid}',
        'ng-minlength' => '10',
        )) }}
      </div>
      <div>
        <select id="make" name="place" class="form-control">
          <option value="" disabled selected>Interested Work Place
          </option>
          <option value="Yemmiganur">Yemmiganur
          </option>
          <option value="Raichur">Raichur
          </option>
        </select>
      </div>
      <br>
      <div>
        Interested To Work In Night Shift:
        <input type="radio" name="night_shift" value="Yes" > Yes
        <input type="radio" name="night_shift" value="No"> No
      </div>
      <div class="clearfix">
      </div>
      <div class="separator">
        <p class="change_link">New to site?
          <a href="#signup" class="to_register"> Next 
          </a>
        </p>
        <div class="clearfix">
        </div>
      </div>
      <br>
      <a href="{{URL_USERS_LOGIN}}">
        <p class="text-center">{{getPhrase('i_am_having_account')}} 
        </p>
      </a>
    </div>
  </section>
  <div id="register" class="animate form registration_form">
    <section class="login_content">
      {!! Form::open(array('url' => URL_USERS_REGISTER, 'method' => 'POST', 
  'name'=>'formLanguage ', 'novalidate'=>'', 'class'=>"loginform", 
  'name'=>"registrationForm")) !!}
      <!-- <form> -->
      <h1>Registration Form
      </h1>
      <div>
        {{ Form::email('email', $value = null , $attributes = 
   array('class'=>'form-control formclass',
        'placeholder' => getPhrase("email"),
        'ng-model'=>'email',
        'required'=> 'true',
        'ng-class'=>'{"has-error": registrationForm.email.$touched && 
  registrationForm.email.$invalid}',
        )) }}
      </div>
      <div>
        {{ Form::password('password', $attributes = array('class'=>'form- 
  control formclass instruction-call',
        'placeholder' => getPhrase("password"),
        'ng-model'=>'registration.password',
        'required'=> 'true',
        'ng-class'=>'{"has-error": registrationForm.password.$touched && 
  registrationForm.password.$invalid}',
        'ng-minlength' => 5
        )) }}
      </div>
      <div>
        {{ Form::password('password_confirmation', $attributes = 
  array('class'=>'form-control formclass instruction-call',
        'placeholder' => getPhrase("password_confirmation"),
        'ng-model'=>'registration.password_confirmation',
        'required'=> 'true',
        'ng-class'=>'{"has-error": 
  registrationForm.password_confirmation.$touched && 
  registrationForm.password_confirmation.$invalid}',
        'ng-minlength' => 5,
        'compare-to' =>"registration.password"
        )) }}
        {{ Form::text('aadhar_number', $value = null , $attributes = 
  array('class'=>'form-control',
        'placeholder' => "UID (Aadhaar)",
        'required'=> 'true',
        'ng-class'=>'{"has-error": registrationForm.aadhar_number.$touched 
   && registrationForm.aadhar_number.$invalid}',
        'ng-minlength' => '12',
        )) }}
        <br>
      </div>
      <fieldset class="form-group" >
        <input type="file" class="form-control" name="image"
               accept=".png,.jpg,.jpeg" id="image_input">
      </fieldset>
      <?php $parent_module = getSetting('parent', 'module'); ?>
      @if(!$parent_module)
      <input type="hidden" name="is_student" value="0">
      @else
      <div class="row">
        <div class="col-md-6">
          {{ Form::radio('is_student', 0, true, array('id'=>'free')) }}
          <label for="free"> 
            <span class="fa-stack radio-button"> 
              <i class="mdi mdi-check active">
              </i> 
            </span> {{getPhrase('i_am_an_admin')}}
          </label>
        </div>
        <div class="col-md-6">
          {{ Form::radio('is_student', 0, true, array('id'=>'free')) }}
          <label for="free"> 
            <span class="fa-stack radio-button"> 
              <i class="mdi mdi-check active">
              </i> 
            </span> {{getPhrase('i_am_a_student')}}
          </label>
        </div>
      </div>
      @endif
      <div class="text-center buttons">
        <button type="submit"  class="btn btn-default submit"
                ng-disabled='!registrationForm.$valid'> 
  {{getPhrase('register_now')}}
        </button>
      </div>
      {!! Form::close() !!}
      <div class="clearfix">
      </div>
      <div class="separator">
        <p class="change_link">Already a member ?
          <a href="#signin" class="to_register"> Previous 
          </a>
        </p>
        <div class="clearfix">
        </div>
      </div>
    </section>
  </div>
</div>
@stop
@section('footer_scripts')
@include('common.validations')
@stop

AuthController.php验证控制器.php

<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use \Auth;
use Socialite;
use Exception;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/

use AuthenticatesAndRegistersUsers, ThrottlesLogins;

/**
 * Where to redirect users after login / registration.
 *
 * @var string
 */
protected $redirectTo = '/';
protected $dbuser = '';
protected $provider = '';


/**
 * Create a new authentication controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}

/**
 * Get a validator for an incoming registration request.
 *
 * @param  array  $data
 * @return \Illuminate\Contracts\Validation\Validator
 */
protected function validator(array $data)
{
    return Validator::make($data, [
        'username' => 'required|max:255|unique:users',
        // 'name' => 'required|max:255',
        'email' => 'required|email|max:255|unique:users',
        'aadhar_number' => 'required|max:12|unique:users',
        'password' => 'required|min:6|confirmed',
        'image' => 'bail',
        'place' => 'required',
        'night_shift' => 'required',
    ]);
}

/**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return User
 */
protected function create(array $data )
{

    $type = 'student';
    if($data['is_student'])
        $type = 'parent';

    $role = getRoleData($type);

    $user           = new User();
    $user->username     = $data['username'];
    $user->rollnumber     = $data['rollnumber'];
    $user->branch     = $data['branch'];

    $user->email    = $data['email'];
    $user->password = bcrypt($data['password']);
    $user->role_id  = $role;
    $user->image = $data['image'];
    $user->place = $data['place'];
    $user->night_shift = $data['night_shift'];
    $user->phone = $data['phone'];
    $user->aadhar_number = $data['aadhar_number'];
    $user->slug     = $user->makeSlug($user->username);

    $user->save();

    $user->roles()->attach($user->role_id);
    try{
        $this->sendPushNotification($user);
    sendEmail('registration', array('user_name'=>$user->name, 
 'username'=>$data['username'], 'to_email' => $user->email, 
 'password'=>$data['password'], 'aadhar_number' => $user->aadhar_number));

      }
     catch(Exception $ex)
    {

    }

    flash('success','record_added_successfully', 'success');

    $options = array(
                        'name' => $user->name,
                        'image' => getProfilePath($user->image),
                        'slug' => $user->slug,
                        'role' => getRoleData($user->role_id),
                    );
    pushNotification(['owner','admin'], 'newUser', $options);
     return $user;
}



  public function sendPushNotification($user)
 {
    if(getSetting('push_notifications', 'module')) {
      if(getSetting('default', 'push_notifications')=='pusher') {
          $options = array(
                'name' => $user->name,
                'image' => getProfilePath($user->image),
                'slug' => $user->slug,
                'role' => getRoleData($user->role_id),
            );

        pushNotification(['owner','admin'], 'newUser', $options);
      }
      else {
        $this->sendOneSignalMessage('New Registration');
      }
    }
 }


/**
 * This is method is override from Authenticate Users class
 * This validates the user with username or email with the sent password
 * @param  Request $request [description]
 * @return [type]           [description]
 */
protected function processUpload(Request $request, User $user)
 {

   if(env('DEMO_MODE')) {
    return 'demo';
   }

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

      $imageObject = new ImageSettings();

      $destinationPath      = $imageObject->getProfilePicsPath();
      $destinationPathThumb = $imageObject->getProfilePicsThumbnailpath();

      $fileName = $user->id.'.'.$request->image->guessClientExtension();
      ;
      $request->file('image')->move($destinationPath, $fileName);
      $user->image = $fileName;

      Image::make($destinationPath.$fileName)->fit($imageObject- 
 >getProfilePicSize())->save($destinationPath.$fileName);

      Image::make($destinationPath.$fileName)->fit($imageObject- 
 >getThumbnailSize())->save($destinationPathThumb.$fileName);
      $user->save();
    }
 }

public function postLogin(Request $request)
{
    $login_status = FALSE;
    if (Auth::attempt(['aadhar_number' => $request->email, 'password' => 
 $request->password])) {
            // return redirect(PREFIX);
            $login_status = TRUE;
    }

    elseif (Auth::attempt(['email'=> $request->email, 'password' => 
 $request->password])) {
        $login_status = TRUE;
    }

    if(!$login_status)
    {
           return redirect()->back()
        ->withInput($request->only($this->loginUsername(), 'remember'))
        ->withErrors([
            $this->loginUsername() => $this->getFailedLoginMessage(),
        ]);
    }

    /**
     * Check if the logged in user is parent or student
     * if parent check if admin enabled the parent module
     * if not enabled show the message to user and logout the user
     */

    if($login_status) {
        if(checkRole(getUserGrade(7)))  {
           if(!getSetting('parent', 'module')) {
            return redirect(URL_PARENT_LOGOUT);
           }
        }
    }

    /**
     * The logged in user is student/admin/owner
     */
        if($login_status)
        {
            return redirect(PREFIX);
        }




}


 /**
 * Redirect the user to the GitHub authentication page.
 *
 * @return Response
 */
public function redirectToProvider($logintype)
{

    if(!getSetting($logintype.'_login', 'module'))
    {
        flash('Ooops..!', $logintype.'_login_is_disabled','error');
         return redirect(PREFIX);
    }
    $this->provider = $logintype;
    return Socialite::driver($this->provider)->redirect();

}

 /**
 * Obtain the user information from GitHub.
 *
 * @return Response
 */
public function handleProviderCallback($logintype)
{

    try{
    $user = Socialite::driver($logintype);


    if(!$user)
    {
        return redirect(PREFIX);
    }

    $user = $user->user();


     if($user)
     {

        if($this->checkIsUserAvailable($user)) {
            Auth::login($this->dbuser, true);
            flash('Success...!', 'log_in_success', 'success');
            return redirect(PREFIX);
        }
        flash('Ooops...!', 'faiiled_to_login', 'error');
        return redirect(PREFIX);
     }
 }
     catch (Exception $ex)
     {
        return redirect(PREFIX);
     }
}

public function checkIsUserAvailable($user)
{

    $id         = $user->getId();
    $nickname   = $user->getNickname();
    $name       = $user->getName();
    $email      = $user->getEmail();
    $avatar     = $user->getAvatar();

    $this->dbuser = User::where('email', '=',$email)->first();

    if($this->dbuser) {
        //User already available return true
        return TRUE;
    }

    $newUser = array(
                        'name' => $name,
                        'email'=>$email,
                    );
    $newUser = (object)$newUser;

    $userObj = new User();
   $this->dbuser = $userObj->registerWithSocialLogin($newUser);
   $this->dbuser = User::where('slug','=',$this->dbuser->slug)->first();
   // $this->sendPushNotification($this->dbuser);
   return TRUE;

}

public function socialLoginCancelled(Request $request)
{
     return redirect(PREFIX);
}

} }

First, you should urgently consider updating Laravel to newer versions.首先,您应该紧急考虑将 Laravel 更新到更新的版本。 Second, I think you are missing enctype="multipart/form-data" accept-charset="UTF-8" in your form tag其次,我认为您的表单标签中缺少enctype="multipart/form-data" accept-charset="UTF-8"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM