Laravel 5.2 Upload Image to uploads folder while user registration - php

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. Please can any one suggest me, thank you.
Please find below is my 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
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.
Second, I think you are missing enctype="multipart/form-data" accept-charset="UTF-8" in your form tag

Related

I can't store a new user on an app depoed on herou

I created a laravel 8 app in which i can store a new user, locally it works fine but when deployed on heroku at the moment i mike to create a new user this error message appears:
"Trying to access array offset on value of type null"
here is the user class:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Auth\Notifications\ResetPassword;
use Hash;
/**
* Class User
*
* #package App
* #property string $name
* #property string $email
* #property string $password
* #property string $role
* #property string $remember_token
* #property string $citizen
*/
class User extends Authenticatable
{
use Notifiable;
protected $fillable = ['name', 'email', 'password', 'remember_token', 'role_id', 'citizen_id'];
protected $hidden = ['password', 'remember_token'];
public static function boot()
{
parent::boot();
User::observe(new \App\Observers\UserActionsObserver);
}
/**
* Hash password
* #param $input
*/
public function setPasswordAttribute($input)
{
if ($input)
$this->attributes['password'] = app('hash')->needsRehash($input) ? Hash::make($input) : $input;
}
/**
* Set to null if empty
* #param $input
*/
public function setRoleIdAttribute($input)
{
$this->attributes['role_id'] = $input ? $input : null;
}
/**
* Set to null if empty
* #param $input
*/
public function setCitizenIdAttribute($input)
{
$this->attributes['citizen_id'] = $input ? $input : null;
}
public function role()
{
return $this->belongsTo(Role::class, 'role_id');
}
public function citizen()
{
return $this->belongsTo(Citizen::class, 'citizen_id')->withTrashed();
}
public function sendPasswordResetNotification($token)
{
$this->notify(new ResetPassword($token));
}
}
here is the controller class:
<?php
namespace App\Http\Controllers\Admin;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\StoreUsersRequest;
use App\Http\Requests\Admin\UpdateUsersRequest;
class UsersController extends Controller
{
/**
* Display a listing of User.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
if (! Gate::allows('user_access')) {
return abort(401);
}
$users = User::all();
return view('admin.users.index', compact('users'));
}
/**
* Show the form for creating new User.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
if (! Gate::allows('user_create')) {
return abort(401);
}
$roles = \App\Role::get()->pluck('title', 'id')->prepend(trans('quickadmin.qa_please_select'), '');
$citizens = \App\Citizen::get()->pluck('num_cin', 'id')->prepend(trans('quickadmin.qa_please_select'), '');
return view('admin.users.create', compact('roles', 'citizens'));
}
/**
* Store a newly created User in storage.
*
* #param \App\Http\Requests\StoreUsersRequest $request
* #return \Illuminate\Http\Response
*/
public function store(StoreUsersRequest $request)
{
if (! Gate::allows('user_create')) {
return abort(401);
}
$user = User::create($request->all());
return redirect()->route('admin.users.index');
}
/**
* Show the form for editing User.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
if (! Gate::allows('user_edit')) {
return abort(401);
}
$roles = \App\Role::get()->pluck('title', 'id')->prepend(trans('quickadmin.qa_please_select'), '');
$citizens = \App\Citizen::get()->pluck('num_cin', 'id')->prepend(trans('quickadmin.qa_please_select'), '');
$user = User::findOrFail($id);
return view('admin.users.edit', compact('user', 'roles', 'citizens'));
}
/**
* Update User in storage.
*
* #param \App\Http\Requests\UpdateUsersRequest $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(UpdateUsersRequest $request, $id)
{
if (! Gate::allows('user_edit')) {
return abort(401);
}
$user = User::findOrFail($id);
$user->update($request->all());
return redirect()->route('admin.users.index');
}
/**
* Display User.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
if (! Gate::allows('user_view')) {
return abort(401);
}
$roles = \App\Role::get()->pluck('title', 'id')->prepend(trans('quickadmin.qa_please_select'), '');
$citizens = \App\Citizen::get()->pluck('num_cin', 'id')->prepend(trans('quickadmin.qa_please_select'), '');$user_actions = \App\UserAction::where('user_id', $id)->get();
$user = User::findOrFail($id);
return view('admin.users.show', compact('user', 'user_actions'));
}
/**
* Remove User from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
if (! Gate::allows('user_delete')) {
return abort(401);
}
$user = User::findOrFail($id);
$user->delete();
return redirect()->route('admin.users.index');
}
/**
* Delete all selected User at once.
*
* #param Request $request
*/
public function massDestroy(Request $request)
{
if (! Gate::allows('user_delete')) {
return abort(401);
}
if ($request->input('ids')) {
$entries = User::whereIn('id', $request->input('ids'))->get();
foreach ($entries as $entry) {
$entry->delete();
}
}
}
}
finally here is the creation view:
#extends('layouts.app')
#section('content')
<h3 class="page-title">المستخدم</h3>
{!! Form::open(['method' => 'POST', 'route' => ['admin.users.store']]) !!}
<div class="panel panel-default">
<div class="panel-heading">
#lang('quickadmin.qa_create')
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 form-group">
{!! Form::label('name', trans('quickadmin.users.fields.name').'*', ['class' => 'control-label']) !!}
{!! Form::text('name', old('name'), ['class' => 'form-control', 'placeholder' => '', 'required' => '']) !!}
<p class="help-block"></p>
#if($errors->has('name'))
<p class="help-block">
{{ $errors->first('name') }}
</p>
#endif
</div>
</div>
<div class="row">
<div class="col-xs-12 form-group">
{!! Form::label('email', trans('quickadmin.users.fields.email').'*', ['class' => 'control-label']) !!}
{!! Form::email('email', old('email'), ['class' => 'form-control', 'placeholder' => '', 'required' => '']) !!}
<p class="help-block"></p>
#if($errors->has('email'))
<p class="help-block">
{{ $errors->first('email') }}
</p>
#endif
</div>
</div>
<div class="row">
<div class="col-xs-12 form-group">
{!! Form::label('password', trans('quickadmin.users.fields.password').'*', ['class' => 'control-label']) !!}
{!! Form::password('password', ['class' => 'form-control', 'placeholder' => '', 'required' => '']) !!}
<p class="help-block"></p>
#if($errors->has('password'))
<p class="help-block">
{{ $errors->first('password') }}
</p>
#endif
</div>
</div>
<div class="row">
<div class="col-xs-12 form-group">
{!! Form::label('role_id', trans('quickadmin.users.fields.role').'*', ['class' => 'control-label']) !!}
{!! Form::select('role_id', $roles, old('role_id'), ['class' => 'form-control select2', 'required' => '']) !!}
<p class="help-block"></p>
#if($errors->has('role_id'))
<p class="help-block">
{{ $errors->first('role_id') }}
</p>
#endif
</div>
</div>
<div class="row">
<div class="col-xs-12 form-group">
{!! Form::label('citizen_id', trans('quickadmin.users.fields.citizen').'', ['class' => 'control-label']) !!}
{!! Form::select('citizen_id', $citizens, old('citizen_id'), ['class' => 'form-control select2']) !!}
<p class="help-block"></p>
#if($errors->has('citizen_id'))
<p class="help-block">
{{ $errors->first('citizen_id') }}
</p>
#endif
</div>
</div>
</div>
</div>
{!! Form::submit(trans('quickadmin.qa_save'), ['class' => 'btn btn-danger']) !!}
{!! Form::close() !!}
#stop

SQLSTATE [23000]: Integrity limitation violation: 1062 'mail#mail.com' duplicate entry for 'users_email_unique' key

I have a registration form. When the email is registered in the database it gets an error message
SQLSTATE [23000]: Violation of integrity restrictions: 1062 Duplicate entry 'mail#mail.com' for 'users_email_unique' key
I want to avoid that mistake and instead get a warning like "registered email" or something similar. Any help is appreciated. This is my code.
controller/auth/registercontroller.php
<?php
namespace VMS\Http\Controllers\Auth;
use VMS\User;
use VMS\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* 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, [
'name' => 'required|min:4',
'id_level' => 'required',
'email' => 'required|min:4|email|unique:users',
'password' => 'required',
'confirm' => 'required|same:password',
'g-recaptcha-response' => 'required|captcha',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \VMS\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'id_level' => $data['id_level'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
public function store(Request $request)
{
$name = $request->input('name');
$id_level = $request->input('id_level');
$email = $request->input('email');
$password = $request->input('password');
$user = User::create([
'name' => $name,
'id_level' => $id_level,
'email' => $email,
'password' => Hash::make($password)
]);
if($user) {
return response()->json([
'success' => true,
'message' => 'Register Berhasil!'
], 201);
} else {
return response()->json([
'success' => false,
'message' => 'Register Gagal!'
], 400);
}
}
}
User.php (Model)
<?php
namespace VMS;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'id_level', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
protected $connection = 'vms_db';
}
register.blade.php
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>SI-BeLa</title>
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}" defer></script>
<!-- Fonts -->
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght#0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet">
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div id="app">
<main class="py-4">
<div class="container" style="margin: 0; min-width: 100%">
<div class="row">
<div class="col-sm-6" style="text-align: ; padding-right: 20px;">
#guest
<a class="logo" href="{{ url('/') }}">{{ __('SI-BeLa') }}</a>
#endguest
</div>
<div class="col-sm-6" style="text-align: center;">
<h2 class="title">
<br><br>
<div style="text-align: center;">REGISTER
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ route('register') }}" method="post">
{{ csrf_field() }}
<div class="cont_form_sign_up text-center">
<br>
<input type="text" class="form-control2" placeholder="Nama" id="name" name="name" pattern=".{4,}" required="required" title="Paling sedikit 4 karakter">
<p style="font-size:12px; color:red; text-align:left; padding-left: 17%;" >* Nama paling sedikit 4 Karakter</p>
<input type="hidden" class="form-control2" value="9" id="id_level" name="id_level">
<input type="email" class="form-control2" placeholder="E-mail" id="email" name="email" required="required" pattern="[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+">
<p style="font-size:12px; color:red; text-align:left; padding-left: 17%;" >* Email harus aktif & Pastikan email belum terdaftar di SIBeLa</p>
<input type="password" id="pw1" name="password" class="form-control2" placeholder="Password"
required="required" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}">
<p style="font-size:12px; color:red; text-align:left; padding-left: 17%;" >* Password paling sedikit 8 karakter serta mengandung angka, huruf kecil dan besar</p>
<input type="password" id="pw2" name="confirm" class="form-control2" placeholder="Confirm Password" required="required">
<div class="form-group">
<center>
{!! NoCaptcha::renderJs() !!}
{!! NoCaptcha::display() !!}
<span class="text-danger">{{ $errors->first('g-recaptcha-response') }}</span>
</center>
</div>
<a class="btn btn-linkk" href="/loginpl">
{{ __('Kembali ke login') }}
</a>
<br>
<button class="button gd-btn btn-2 btn-primaryy" onclick="cambiar_sign_up()"><strong>REGISTER</strong> </button>
</div>
</form>
</div>
</h2>
</div>
</div>
</div>
</main>
How do I make a notification alert if the email is registered?
You have to use like this. Remove unique:users from validation
return Validator::make($data, [
'name' => 'required|min:4',
'id_level' => 'required',
'email' => 'required|min:4|email',
'password' => 'required',
'confirm' => 'required|same:password',
'g-recaptcha-response' => 'required|captcha',
]);
you must use laravel validation in your controller for validate request parameters.
first add this use top of your controller
use Illuminate\Support\Facades\Validator;
then in your registercontroller define this method
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email|unique:users',
'password' => 'required|max:10',
'name' => 'nullable|string|max:50',
]);
if ($validator->fails()) {
$response = $validator->errors();
session()->flash('flash_error', $response);
return redirect()->back();
}
/**
* create new user
*/
try {
/**
* new user
*/
User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
} catch (Exception $e) {
throw new HttpException(500, $e->getMessage());
}
session()->flash('flash_success', 'you are registered.');
return redirect()->back();
}
by default email field in laravel is unique and for validate it we use this exception :
unique:users
users is table name.
to learn more about laravel validation
see this link
https://laravel.com/docs/7.x/validation
to access validation errors in view file
we pass errors flash session with name flash_error
you can show it for example like this:
#if(session()->has('flash_error'))
<ul>
#foreach(session()->get('flash_error') as $error)
<li>{{ session()->get('flash_error') }}</li>
#endforeach
</ul>
#endif
and show success message with bootstrap like this:
#if(session()->has('flash_success'))
<div class="alert alert-success" role="alert">
{{ session()->get('flash_success') }}
</div>
#endif

I'm getting strange error Method Illuminate\Http\UploadedFile::backup does not exist

I'm trying on Laravel with "Intervention image" package to resize uploaded image 2x times with different resolution. That why i used backup() method to store original resolution of picture before process of resizing is made. But when i run my code I'm getting the error "Method Illuminate\Http\UploadedFile::backup does not exist." Does anyone knows where is a problem ?
Create.blade.php
#extends('layout')
#section('content')
<div class="container2">
<div class="container">
<div class="card card-container">
<!-- <img class="profile-img-card" src="//lh3.googleusercontent.com/-6V8xOA6M7BA/AAAAAAAAAAI/AAAAAAAAAAA/rzlHcD0KYwo/photo.jpg?sz=120" alt="" /> -->
<h1 style="text-align: center;">Napiši Vijest</h1>
#if(count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach($errors ->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
{!! Form::open(['action' => 'MainController#store', 'method' => 'POST', 'files' => true]) !!}
<div class="form-group">
{{Form::label('postName', 'Ime')}}
{{Form::text('postName', '', ['id' => 'postName', 'class' => ($errors->has('postName')) ? 'form-control is-invalid' : 'form-control', 'placeholder' => 'Unesite naslov'])}}
</div>
<div class="form-group">
{{Form::label('naslov', 'Naslov')}}
{{Form::text('naslov', '', ['id' => 'inputname', 'class' => ($errors->has('naslov')) ? 'form-control is-invalid' : 'form-control', 'placeholder' => 'Unesite naslov'])}}
</div>
<div class="form-group">
{{Form::label('sadržaj', 'Sadržaj')}}
{{Form::textarea('sadržaj', '', ['id' => 'inputtext', 'class' => ($errors->has('sadržaj')) ? 'form-control is-invalid' : 'form-control', 'placeholder' => 'Unesite sadržaj'])}}
</div>
<div class="form-group">
{{Form::label('file', 'Izaberi fajl')}}
{{ Form::file('file') }}
</div>
<div class="form-group">
{{Form::label('slika', 'Izaberi sliku')}}
{{Form::file('slika')}}
</div>
<div class="form-group">
{{Form::label('Category', 'Izaberi kategoriju')}}
{{Form::select('category', $category, null) }}
</div>
{{Form::submit('Prihvati', ['class' => 'btn btn-success']) }}
Početna strana
{!! Form::close() !!}
</div><!-- /card-container -->
</div><!-- /container -->
</div><!-- /container -->
#endsection
Web.php
Route::get('/createPost', 'MainController#create')->name('post.create')->middleware('admin');
Controller.php
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use App\Http\Request2;
//including post model to controller
use validate;
use App\Post;
use App\Document;
use App\Category;
//if we want to use sql syntax for queries
use DB;
use File;
use Image;
use Mail;
use Session;
USE Validator;
use Redirect;
use Illuminate\Support\Facades\Input;
class MainController extends Controller
{
public function create()
{
$category = Category::pluck('title', 'id');
return View('create', compact('category',$category));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$rules = [
'naslov' => 'required|min:3|max:20',
'sadržaj' => 'required|min:40',
'slika' => 'mimes:jpeg,bmp,png'
];
$customMessages = [
'required' => 'Unesite ":attribute" !',
'min' => 'Polje ":attribute" mora da ima minimum :min karaktera.',
'max' => 'Polje ":attribute" može da ima najviše :max karaktera.',
'email' => 'Polje ":attribute" mora da ima validan format',
'mimes' => '":attribute" mora biti u sledećim formatima: :values'
];
$validator = Validator::make(Input::all(), $rules, $customMessages);
if ($validator->fails())
{
return \Redirect::back()->withErrors($validator)->withInput();
}
//create new post
$post= new Post;
$post -> name = $request -> input('postName');
$post -> title = $request -> input('naslov');
$post -> content = $request -> input('sadržaj');
$post -> category_id = $request -> input('category');
// Handle File Upload
if( $request->hasFile('file') ) {
$filenameWithExt = $request->file('file')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('file')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('file')->storeAs('public/upload', $fileNameToStore);
$post->file_name = $fileNameToStore;
}
// Check if file is present
if( $request->hasFile('slika') ) {
$post_thumbnail = $request->file('slika');
$filename = time() . '.' . $post_thumbnail->getClientOriginalExtension();
$post_thumbnail->backup();
ini_set('memory_limit', '256M');
$filename=Image::make($post_thumbnail);
$filename->resize(329.33, 199.33)->save( public_path('uploads/' . $filename ) );
$post->post_thumbnail = $filename;
}
$post->save();
return redirect()->route('posts.show', $post)->with('successPost', 'Napisali ste novu vijest !');
}
}
You can do that,
//$post_thumbnail = Image::make($request->file('slika'));
// $post_thumbnail->backup();
$post_thumbnail = $request->file('slika');
$filename = time() . '.' . $post_thumbnail->getClientOriginalExtension();
Image::make($post_thumbnail)->backup();
ini_set('memory_limit', '256M');
// $filename=Image::make($post_thumbnail);

Laravel display name from database

I have a new problem. I'll try to give enough information.
I'm trying to display the names of the employees that have visited the customers, but as you can see it displays the names of the customers. Instead of Bryan or Granucci (these are the customers), it should say Madmin (I have only one user at the moment).
Screenshot
This is the drafts page
I'll add the code form my view, controller and model.
Drafts View
#extends('app')
#section('content')
#include('nav')
<div class="container">
#include('flash')
<div class="row">
<div class="col-md-2">
{!! Form::open(['method' => 'GET', 'action' => 'DraftsController#create']) !!}
{!! Form::submit('Create new draft', ['class' => 'btn btn-primary form-control']) !!}
{!! Form::close() !!}
</div>
</div>
<hr>
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">Search drafts</div>
<div class="panel-body">
{!! Form::open(array('url' => 'drafts/search', 'method' => 'post')) !!}
<div class="form-group">
<div class="col-md-2" align="right">
{!! Form::label('customer_name', 'Customer:') !!}
</div>
<div class="col-md-6">
{!! Form::text('customer_name', null, ['class' => 'form-control typeahead tt-query', 'autocomplete' => 'off', 'spellcheck' => 'false', 'placeholder' => 'Search...']) !!}
</div>
<div class="col-md-2" align="right">
{!! Form::label('customer_id', 'Customer ID:') !!}
</div>
<div class="col-md-2">
{!! Form::text('customer_id', null, ['class' => 'form-control', 'readonly' => 'readonly']) !!}
</div>
</div>
<br><br>
<div class="form-group">
<div class="col-md-2" align="right">
{!! Form::label('descr', 'Article:') !!}
</div>
<div class="col-md-6">
{!! Form::text('descr', null, ['class' => 'form-control typeahead tt-query', 'autocomplete' => 'off', 'spellcheck' => 'false', 'placeholder' => 'Search...']) !!}
{!! Form::hidden('reportgroup', null, ['class' => 'form-control']) !!}
</div>
<div class="col-md-2" align="right">
{!! Form::label('article_id', 'Article ID:') !!}
</div>
<div class="col-md-2">
{!! Form::text('article_id', null, ['class' => 'form-control', 'readonly' => 'readonly']) !!}
</div>
</div>
<br><br>
<div class="form-group">
<div class="col-md-2" align="right">
{!! Form::label('reference', 'Reference:') !!}
</div>
<div class="col-md-10">
{!! Form::text('reference', null, ['class' => 'form-control']) !!}
</div>
</div>
<br><br>
<div class="form-group">
<div class="col-md-12" align="right">
{!! Form::submit('Search', ['class' => 'btn btn-primary form-control']) !!}
</div>
</div>
{!! Form::close() !!}
#include('errors')
</div>
</div>
<div class="panel panel-default">
{!! Form::open(['method' => 'POST', 'action' => 'DraftsController#invoice']) !!}
<div class="panel-heading">Search results</div>
<div class="panel-body">
<table class="table">
<tr>
<th> </th>
<th>No</th>
<th>Employee</th>
<th>Customer</th>
<th>Reference</th>
<th>Draft created</th>
<th>Work date</th>
<th style="text-align:right">Total excl. VAT</th>
<th> </th>
</tr>
<?php $count = 0; ?>
#foreach ($result as $draft)
<tr>
<td><input type="checkbox" id="invoice_{{$draft['id']}}" name="invoice_{{$draft['id']}}"></td>
<td>{{ $draft['id'] }}</td>
<td>{{$draft['name'] }} ({{ $draft['user_id'] }})</td>
<td>{{$draft['name'] }} ({{ $draft['customer_id'] }})</td>
<td>{{ $draft['reference'] }}</td>
<td>{{ $draft['created_at'] }}</td>
<td></td>
<td style="text-align:right">{{ number_format($totals[$draft['id']],2) }}</td>
<td><input class="btn btn-danger" name="delete_{{$draft['id']}}" id="delete_{{$draft['id']}}" type="submit" value="X"></td>
</tr>
<?php $count++ ?>
#endforeach
</table>
<?php
if ($count == 0) {
print "No results";
}
else {
?>
<table>
<tr>
<td>
{!! Form::submit('Create invoice for selected drafts', ['class' => 'btn btn-primary form-control']) !!}
</td>
<td>
with invoice date
</td>
<td>
<input class="form-control" name="createDate" type="date" id="createDate" value="{{date('Y-m-d')}}">
</td>
<td>
and mail them to customer
</td>
<td>
<input type="checkbox" id="mailThem" name="mailThem">
</td>
</tr>
</table>
{!! Form::close() !!}
<?php
}
?>
</div>
</div>
</div>
</div>
</div>
#include('jsonArticles')
#include('jsonCustomers')
<script src="{{ asset('/js/typeahead.js') }}"></script>
<script src="{{ asset('/js/customers.js') }}"></script>
<script src="{{ asset('/js/articles.js') }}"></script>
#stop
Draftsheader Model
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class DraftHeader extends Model {
public function customer()
{
return $this->belongsTo('App\Customer');
}
public function user()
{
return $this->belongsTo('App\User');
}
public function lines()
{
return $this->hasMany('App\DraftLine');
}
protected $fillable = [
'user_id',
'employee_name',
'customer_id',
'name',
'name2',
'address',
'postcode',
'town',
'country',
'reference'
];
}
Drafts Controller
<?php
namespace App\Http\Controllers;
use Session;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Article;
use App\Customer;
use App\User;
use App\DraftHeader;
use App\DraftLine;
use App\InvoiceHeader;
use App\InvoiceLine;
use App\InvoiceMail;
use App\Http\Requests\DraftRequest;
use App\Http\Requests\DraftSearchRequest;
use App\Http\Requests\DraftLinesRequest;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
class DraftsController extends Controller {
/*
|--------------------------------------------------------------------------
| ArticlesController
|--------------------------------------------------------------------------
|
| Controller for Metis draft tasks
|
*/
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct() {
$this->middleware('auth:admin');
}
/**
* Get all articles
*
* #return array()
*/
private function allArticles() {
$allArticles = array();
$ff = Article::All()->toArray();
foreach ($ff as $ff1) {
$allArticles[] = array('name' => $ff1['descr'], 'id' => $ff1['id']);
}
return $allArticles;
}
/**
* Get all customers
*
* #return array()
*/
private function allCustomers() {
$allCustomers = array();
$ff = Customer::All()->toArray();
foreach ($ff as $ff1) {
$allCustomers[] = array('name' => $ff1['name'], 'id' => $ff1['id']);
}
return $allCustomers;
}
/**
* Get all uers
*
* #return array()
*/
private function allUsers() {
$allUsers = array();
$ff = User::All()->toArray();
foreach ($ff as $ff1) {
$allUsers[] = array('name' => $ff1['name'], 'id' => $ff1['id']);
//dd($allUsers);
}
return $allUsers;
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index() {
// Use request saved in session if applicable
$result = array();
if (Session::has('draft_search_request')) {
$request = Session::get('draft_search_request');
//dd($request);
$result = DraftHeader::query();
if (strlen(trim($request['customer'])) > 0) {
$result->where('name', 'LIKE', "%" . $request['customer'] . "%");
}
if (strlen(trim($request['user'])) > 0) {
$result->where('name', 'LIKE', "%" . $request['user'] . "%");
}
if (strlen(trim($request['reference'])) > 0) {
$result->where('reference', 'LIKE', "%" . $request['reference'] . "%");
}
if (strlen(trim($request['article'])) > 0) {
$result->DraftLine()->where('descr', 'LIKE', "%" . $request['article'] . "%");
}
//dd($result->toSql());
$result = $result->get()->toArray();
//dd($result);
}
else {
$result = DraftHeader::query()->where('created_at', '>', Carbon::yesterday())->get()->toArray();
}
// Get the total amount for each draft draft
$totals = array();
foreach ($result as $value) {
$total = DraftLine::selectRaw('sum(qty*netamount) AS total')->where('draft_header_id', '=', $value['id'])->get()->toArray();
$totals[$value['id']] = $total[0]['total'];
}
return view('drafts.search')->with('result', $result)->with('totals', $totals)->with('allArticles', $this->allArticles())->with('allCustomers', $this->allCustomers())->with('allUsers', $this->allUsers());
}
public function search(DraftSearchRequest $request) {
//Put request in session variable to use in view
$request1 = array('customer' => $request['customer'],'user' => $request['user'], 'reference' => $request['reference'], 'article' => $request['article']);
if ($request1['customer'] == "" && $request1['user'] == "" && $request1['reference'] == "" && $request1['article'] == "") {
session()->flash('draft_search_request', $request1);
}
else {
Session::put('draft_search_request', $request1);
}
return redirect ('drafts');
}
public function invoice(Request $request) {
//Create invoices for the selected drafts
//dd($request);
//dd($request->except('_token'));
$number_of_invoices = 0;
$draftdeleted = false;
$mail = false;
if (isset($request['mailThem']) && $request['mailThem'] == "on") {
$mail = true;
}
$invoicedate = $request['createDate'];
if (!checkdate(substr($invoicedate, 5, 2), substr($invoicedate, 8, 2), substr($invoicedate, 0, 4))) {
$invoicedate = "";
}
foreach($request->except('_token') as $key => $val) {
//dd($key);
if (substr($key, 0, 8) == "invoice_" && $val == "on") {
$draft_id = substr($key, 8);
// Create the invoice
// But only if there are lines
$draftheader = DraftHeader::findOrFail($draft_id)->toArray();
$draftlines = DraftHeader::findOrFail($draft_id)->lines()->get()->toArray();
if (count($draftlines) > 0) {
// Create the invoice header
$invoiceheader = InvoiceHeader::create($draftheader);
if ($invoicedate != "") {
$invoiceheader->created_at = $invoicedate;
$invoiceheader->save();
}
// Create the invoice lines
foreach ($draftlines as $draftline) {
$newline = new InvoiceLine;
$newline->article_id = $draftline['article_id'];
$newline->descr = $draftline['descr'];
$newline->qty = $draftline['qty'];
$newline->grossamount = $draftline['grossamount'];
$newline->discount = $draftline['discount'];
$newline->netamount = $draftline['netamount'];
$newline->taxrate = $draftline['taxrate'];
$newline->addition = $draftline['addition'];
$newline = $invoiceheader->lines()->save($newline);
}
// Delete the draft
DraftHeader::destroy($draft_id);
$number_of_invoices++;
if ($mail) {
// Add the invoice to the create and send queue (no recipient = to be processed)
$invoicemail = new InvoiceMail;
$invoicemail = $invoiceheader->mail()->save($invoicemail);
}
}
}
if (substr($key, 0, 7) == "delete_") {
// Delete the selected draft
$draft_id = substr($key, 7);
DraftHeader::destroy($draft_id);
session()->flash('flash_success', "Draft deleted");
$draftdeleted = true;
}
}
$andmailed = "";
if ($number_of_invoices > 0 && $mail) {
$andmailed = " and queued to be sent by mail";
}
if (!$draftdeleted) {
session()->flash('flash_success', $number_of_invoices . " invoice(s) created " . $andmailed);
}
$request1 = array('customer' => $request['customer'], 'user' => $request['user'], 'reference' => $request['reference'], 'article' => $request['article']);
if ($request1['customer'] == "" && ['user'] == "" && $request1['reference'] == "" && $request1['article'] == "") {
session()->flash('draft_search_request', $request1);
}
else {
Session::put('draft_search_request', $request1);
}
return redirect ('drafts');
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create() {
return view('drafts.create')->with('allCustomers', $this->allCustomers());
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(DraftRequest $request) {
//dd($request);
// Get the customer information
/*
$this->validate($request, [
'reference' => 'required'
]);
*
*/
$customer = Customer::findOrFail($request['customer_id']);
$pass = array_merge($request->all(), $customer->toArray());
//dd($pass);
DraftHeader::create($pass);
//dd($request);
// Get the user information
/*
$this->validate($request, [
'reference' => 'required'
]);
*
*/
$user = User::findOrFail($request['user_id']);
$pass = array_merge($request->all(), $user->toArray());
//dd($pass);
DraftHeader::create($pass);
return redirect('drafts');
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id) {
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id) {
// Retrieve header and lines
//dd($id);
$draftheader = DraftHeader::findOrFail($id)->toArray();
//dd($draftheader);
$draftlines = DraftHeader::findOrFail($id)->lines()->get()->toArray();
//dd($draftlines);
// Get the draft's total
$drafttotal = 0;
$drafttotal_in = 0;
foreach ($draftlines as $line) {
$drafttotal = $drafttotal + ($line['qty'] * $line['netamount']);
$drafttotal_in = $drafttotal_in + (($line['qty'] * $line['netamount']) / 100 * (100 + $line['taxrate']));
}
return view('drafts.edit')->with('header', $draftheader)->with('lines', $draftlines)->with('drafttotal', $drafttotal)->with('drafttotal_in', $drafttotal_in)->with('allArticles', $this->allArticles());
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id, DraftLinesRequest $request) {
//dd($request->all());
// Save the draft header (again)
$draftheader = DraftHeader::findOrFail($id);
if ($draftheader->reference != $request['reference']) {
$draftheader->reference = $request['reference'];
$draftheader->save();
}
// Update the lines if there are changes
$requestcopy = $request->All();
reset($requestcopy);
foreach ($requestcopy as $key => $value) {
if (substr($key, 0, 11) == "grossamount") {
$lineid = substr($key, 11);
$draftline = Draftline::findOrFail($lineid);
$v_descr = 'descr' . $lineid;
$v_qty = 'qty' . $lineid;
$v_grossamount = 'grossamount' . $lineid;
$v_discount = 'discount' . $lineid;
$v_addition = 'addition' . $lineid;
if ($draftline->descr != $request[$v_descr] || $draftline->qty != $request[$v_qty] || $draftline->grossamount != $request[$v_grossamount] || $draftline->discount != $request[$v_discount] || $draftline->addition != $request[$v_addition]) {
$draftline->descr = $request[$v_descr];
$draftline->qty = $request[$v_qty];
$draftline->addition = $request[$v_addition];
$draftline->grossamount = $request[$v_grossamount];
$draftline->discount = $request[$v_discount];
$draftline->netamount = $draftline->grossamount - ($draftline->grossamount * ($draftline->discount/100)) + ($draftline->grossamount * ($draftline->addition/100));
$draftline->save();
session()->flash('flash_success', 'Update succeeded');
}
}
}
// Check if a line needs to be deleted
reset($requestcopy);
foreach ($requestcopy as $key => $value) {
if (substr($key, 0, 6) == "cmdDel") {
$lineid = substr($key, 6);
$draftline = Draftline::findOrFail($lineid);
$draftline->delete();
session()->flash('flash_success', 'Draft line was deleted');
}
}
// Check if a new line should be created
if ($request['qty'] != 0 && $request['article_id'] > 0 && strlen($request['descr']) > 0) {
$newline = new DraftLine;
$article = Article::findOrFail($request['article_id']);
$customer = $draftheader->customer;
$newline->article_id = $request['article_id'];
$newline->descr = $request['descr'];
$newline->qty = $request['qty'];
$newline->grossamount = $article->gross;
$newline->discount = $customer->discount;
$newline->taxrate = $article->taxrate;
if ($customer->taxrate == "No tax") {
$newline->taxrate = 0;
}
$newline->netamount = $newline->grossamount - ($newline->grossamount * ($newline->discount/100));
$newline = $draftheader->lines()->save($newline);
session()->flash('flash_success', 'New draft line was added');
}
return redirect('drafts/' . $id . '/edit');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id) {
//
}
}
User model
<?php namespace App;
use App\Hour;
use Illuminate\Notifications\Notifiable;
use Illuminate\Auth\Authenticatable;
use Sofa\Eloquence\Eloquence;
use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
use Notifiable;
use Eloquence;
public function draftheaders()
{
return $this->hasMany('App\DraftHeader');
}
protected $searchableColumns = ['name'];
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
public function hours()
{
return $this->hasMany(Hour::class);
}
}
User controller
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
public function find(Request $request)
{
$term = trim($request->q);
if (empty($term)) {
return \Response::json([]);
}
$users = user::search($term)->limit(5)->get();
$formatted_users = [];
foreach ($users as $user) {
$formatted_users[] = ['id' => $user->id, 'text' => $user->name];
}
return \Response::json($formatted_users);
}
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth')->except('find');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('user');
}
}
The database has the following tables:
User table,
Draftsheader table
In the draftsheader table I changed the column user_id to index. And
in the users table I changed column name to index. Normally I would
index the column and give it a foreignkey. But I looked at the
customer table and the draftsheader table and there where no
foreignkeys. So I was thinking maybe foreignkeys arent nessecary, as
long as the fields are indexed.
I hope you guys can help me out, cause i'm stuck... If information is missing let me now and I'll edit the page.
Update
In the view I changed [¨name¨] to [¨employee_name¨] Like suggested by a fellow stackoverflow user. It resulted in this:
Changed name to employee_name
Try changing this:
#foreach ($result as $draft)
<tr>
<td><input type="checkbox" id="invoice_{{$draft['id']}}" name="invoice_{{$draft['id']}}"></td>
<td>{{ $draft['id'] }}</td>
<td>{{$draft['name'] }} ({{ $draft['user_id'] }})</td>
<td>{{$draft['name'] }} ({{ $draft['customer_id'] }})</td>
<td>{{ $draft['reference'] }}</td>
<td>{{ $draft['created_at'] }}</td>
<td></td>
<td style="text-align:right">{{ number_format($totals[$draft['id']],2) }}</td>
<td><input class="btn btn-danger" name="delete_{{$draft['id']}}" id="delete_{{$draft['id']}}" type="submit" value="X"></td>
</tr>
<?php $count++ ?>
#endforeach
To this:
#foreach ($result as $draft)
<tr>
<td><input type="checkbox" id="invoice_{{$draft['id']}}" name="invoice_{{$draft['id']}}"></td>
<td>{{ $draft['id'] }}</td>
<td>{{$draft['employee_name'] }} ({{ $draft['user_id'] }})</td>
<td>{{$draft['name'] }} ({{ $draft['customer_id'] }})</td>
<td>{{ $draft['reference'] }}</td>
<td>{{ $draft['created_at'] }}</td>
<td></td>
<td style="text-align:right">{{ number_format($totals[$draft['id']],2) }}</td>
<td><input class="btn btn-danger" name="delete_{{$draft['id']}}" id="delete_{{$draft['id']}}" type="submit" value="X"></td>
</tr>
<?php $count++ ?>
#endforeach
You use ['name'] two times, but you have the customer_name on it.

laravel 4 Undefined index: password

My code used to work properly but now there is an error
(ErrorException (E_NOTICE)Undefined index: password)
I really dont know why, so if you know please help me. I searched google for similar exceptions and try everything I see but still no success ... Here is my code
route.php
Route::resource('login', 'LoginController');
LoginController
public function store(){
/*$credentials = array(
'username' => Input::get('username'),
'password' => Hash::make(Input::get('password')),
);*/
if(Auth::attempt(['active' => 1])) {
// if(Auth::attempt($credentials)){
if(Auth::attempt(Input::only('username', 'password'))){
return Auth::user();
//return Redirect::back()->with('message','You are now logged in!');
//return Redirect::to('/')->with('message','You are now logged in!');
}
else{
//$errors = ['password' => "Username and/or password invalid."];
//return Redirect::back()->withErrors($errors)->withInput(Input::except('password'));
return 'Failed~';
}
}
else{
//$errors = ['password' => "Please check your email to activate your account"];
//return Redirect::back()->withErrors($errors)->withInput(Input::except('password'));
return 'Failed~';
}
}
}
View login/create.blade.php
#section('content')
<div class="col-lg-3"></div>
<div class="form col-lg-6 box">
{{ Form::open(['route' => 'login.store'], array('class' => 'form-horizontal')) }}
{{-- #if ($error = $errors->first('password'))
<div class="alert alert-danger">
{{ $error }}
</div>
#endif--}}
<div class="input-group form-group-md">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
{{ Form::text('username', null,['class' => 'form-control','autofocus'=>'autofocus', 'placeholder' => 'Username']) }}
</div>
<div class="input-group form-group-md">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
{{ Form::password('password', array('class' => 'form-control', 'placeholder' => 'Password')) }}
</div>
<div class="form-group-md">
Forgot your password?
</div>
<div class="form-group-md">
{{ Form::submit('Log In', array('class' => 'login navbar-btn btn-block form-control', 'autofocus'=>'autofocus')) }}
</div>
<div class="question form-group-md">
{{ Form::label('register', 'Do not have an account?! ') }} Register here!
</div>
{{ Form::close() }}
</div>
<div class="col-lg-3"> </div>
#stop
error
Rewrite your code as below.
$username = Input::get('username');
$password = Input::get('password');
// You also may add extra conditions to the authenticating query
if (Auth::attempt(array('username' => $username, 'password' => $password, 'active' => 1)))
{
// The user is active, not suspended, and exists.
}else{
// user not exist or suspended
}
Refer this link also.
The problem is that the validateCredentials method which is belongs to your class provider EloquentUserProvider expects that the $credentials array have array element called password and expects it to be hashed .
as shown here :
/**
* Validate a user against the given credentials.
*
* #param \Illuminate\Contracts\Auth\Authenticatable $user
* #param array $credentials
* #return bool
*/
public function validateCredentials(UserContract $user, array $credentials)
{
$plain = $credentials['password'];
return $this->hasher->check($plain, $user->getAuthPassword());
}
and you in your code are sending wrong array in the first attempt call
if(Auth::attempt(['active' => 1]))
to solve this you may have to rewrite your code some thing like this ,
public function store()
{
$credentials = array(
'username' => Input::get('username'),
'password' => Hash::make(Input::get('password')),
'active' => 1
);
if(Auth::attempt($credentials)) {
return Auth::user();
} else {
return 'Failed~';
}
}

Categories