user register form doesnt work in laravel - laravel

i created a new controller called AuthController:
the authentication system that i created is not working :(
<?php
namespace App\Http\Controllers\Site;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class AuthController extends Controller
{
public function register(Request $request)
{
if ($request->isMethod('Get')) {
return view('auth.register');
}
$this->validate($request,[
'fname' => 'required|string|min:3|max:255',
'lname' => 'required|string|min:3|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|string|min:8|max:255|confirmed',
'username' => 'required|string|min:6|max:255|unique:users',
'mobile' => 'required|min:11|max:11|regex:/^09[0-3][0-9]{8}$/u|unique:users'
]);
$user = new User();
$user->fname = $request->fname;
$user->lname = $request->lname;
$user->email = $request->email;
$user->password = Hash::make($request->password);
$user->username = $request->username;
$user->mobile = $request->mobile;
}
public function login()
{
return 'login';
}
public function logout()
{
}
}
and this is my Model:
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'fname', 'lname', 'email', 'password', 'username', 'mobile'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
this is my registration form:
#extends('_partials.master')
#section('title','Register')
#section('stylesheet')
<link rel="stylesheet" href="/assets/css/slick-theme.css">
<link rel="stylesheet" href="/assets/css/slick.css">
<link rel="stylesheet" href="/assets/css/style.css">
#endsection
#section('content')
<article class="single-blog contact-us">
<div class="post-thumb">
<img src="assets/images/archi-feature-cat-6.jpg" alt="">
</div>
<div class="post-content">
<div class="entry-header text-center text-uppercase">
<h2 class="text-left">Register</h2>
</div>
<div class="entry-content">
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirtempor
invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
</p>
</div>
<div class="leave-comment">
<form class="form-horizontal contact-form" method="post"
action="/register">
{{ csrf_field() }}
<div class="form-group">
<div class="col-md-6">
<input type="text" value="{{ #old('fname') }}" class="form-control" id="fname" name="fname"
placeholder="First Name">
<span class="text-danger">{{ $errors->first('fname') }}</span>
</div>
<div class="col-md-6">
<input type="text" value="{{ #old('lname') }}" class="form-control" id="lname" name="lname"
placeholder="Last Name">
<span class="text-danger">{{ $errors->first('lname') }}</span>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input type="text" value="{{ #old('email') }}" class="form-control" id="email" name="email"
placeholder="Email">
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input type="text" value="{{ #old('username') }}" class="form-control" id="username" name="username"
placeholder="Username">
<span class="text-danger">{{ $errors->first('username') }}</span>
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<input type="password" value="{{ #old('password') }}" class="form-control" id="password" name="password"
placeholder="Password">
<span class="text-danger">{{ $errors->first('password') }}</span>
</div>
<div class="col-md-6">
<input type="password" value="{{ #old('password_confirmation') }}" class="form-control" id="password_confirmation" name="password_confirmation"
placeholder="Password Again">
<span class="text-danger">{{ $errors->first('password_confirmation') }}</span>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input type="text" value="{{ #old('mobile') }}" class="form-control" id="mobile" name="mobile"
placeholder="Mobile">
<span class="text-danger">{{ $errors->first('mobile') }}</span>
</div>
</div>
<button type="submit" class="btn send-btn">Register</button>
</form>
</div>
</div>
</article>
#endsection
#section('javascript')
<script src="/assets/js/slick.min.js"></script>
<script src="/assets/js/main.js"></script>
#endsection
my register system dosnt work and it return a blank page.
it doesnt return any error.
i wanna make user Authentication system by myself.
what should i do?
plz help me
tnx
:)

After validating the data, use the create function like this:
$data = $request->all();
$user = User::create([
'fname' => $data->fname;
'lname' => $data->lname;
'email' => $data->email;
'password' => Hash::make($data->password);
'username' => $data->username;
'mobile' => $data->mobile;
]);
Auth::login($user); //this will login the user.

All your code is fine just change $this->validate($request to $this->validate($request->all(),
public function register(Request $request)
{
if ($request->isMethod('Get')) {
return view('auth.register');
}
$this->validate($request->all(),[
'fname' => 'required|string|min:3|max:255',
'lname' => 'required|string|min:3|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|string|min:8|max:255|confirmed',
'username' => 'required|string|min:6|max:255|unique:users',
'mobile' => 'required|min:11|max:11|regex:/^09[0-3][0-9]{8}$/u|unique:users'
]);
$user = new User();
$user->fname = $request->fname;
$user->lname = $request->lname;
$user->email = $request->email;
$user->password = Hash::make($request->password);
$user->username = $request->username;
$user->mobile = $request->mobile;
$user->save(); //add this line
return redirect('login');
}
Add $user->save(); line

Related

Cannot add data for second time but work for firs time, laravel add user

I'm trying to create a form to insert a user but the function doesn't work the second time, only the first. I got *rror after submitting it a second time.
302 found
UserController
class UserController extends Controller
{
// User
public function edit()
{
return view(
'pages.user.edit',
[
'user' => Auth::user(),
'title' => ''
]
);
}
public function create()
{
return view('pages.user.createUS', [
'levels' => Level::get(),
'perusahaans' => Perusahaan::get(),
'satkers' => Satker::get(),
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
public function store(Request $request)
{
// dd($validatedData);
$this->validate(request(), [
'name' => 'required',
'level_id' => 'required',
'satker_id' => 'required',
'username' => ['required', 'string', 'max:255', 'unique:users'],
'phonenumber' => ['required', 'unique:users'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
]);
$errors = $this->errors();
if ($this->fails()) {
return redirect('users/create')->withErrors($errors)->withInput()->with('err', true);
}
// dd($validatedData, $request);
$user = new User([
'name' => request('name'),
'username' => request('username'),
'email' => request('email'),
'phonenumber' => request('phonenumber'),
'level_id' => request('level_id'),
'satker_id' => request('satker_id'),
'remember_token' => Str::random(10)
]);
$user->password = md5(request('password'));
$user->save();
return redirect()->route('users.create')->with('success', 'User Berhasil Dibuat!');
}
/**
* Indicate that the model's email address should be unverified.
*
* #return static
*/
public function unverified()
{
return $this->state(function (array $attributes) {
return [
'email_verified_at' => null,
];
});
}
public function index()
{
$users = User::latest()->get();
$perusahaans = Perusahaan::get();
$satkers = Satker::latest()->get();
return view(
'pages.user.index',
[
'users' => $users,
'perusahaans' => $perusahaans,
'satkers' => $satkers,
'levels' => Level::get()
]
);
}
public function action(Request $request)
{
$pid = $request->post('pid');
$satkers = Satker::where('perusahaan_id', $pid)->latest()->get();
$html = '<option value="">Pilih Satuan Kerja</option>';
foreach ($satkers as $satker) {
$html .= '<option value="' . $satker->id . '">' . $satker->satker . '</option>';
}
echo $html;
// return response()->json(['html' => $html]);
}
// Setting Profile
public function show(User $user)
{
$details = DetailTransaksi::get();
$transaksis = Transaksi::latest()->get();
$tagihans = Tagihan::latest()->get();
$satkers = Satker::latest()->get();
// dd($tagihans->where('user_id', $user->id));
return view('pages.user.detail', [
'user' => $user,
'transaksis' => $transaksis,
'details' => $details,
'tagihans' => $tagihans,
]);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\User $user
* #return \Illuminate\Http\Response
*/
public function update(Request $request)
{
$user = Auth::user();
// $file_name = $request->image->getClientOriginalName();
$rules = [
'name' => 'required',
'username' => 'required',
'satker_id' => 'required',
'email' => 'required',
'phonenumber' => 'required',
'level_id' => 'required',
];
if (
$request->email != $user->email
) {
$rules['email'] = 'required|unique:users';
}
$validatedData = $request->validate($rules);
$validatedData['id'] = auth()->user()->id;
User::where('id', $user->id)
->update($validatedData);
return redirect('/user')->with('success', 'Profile has been Updated');
}
}
Blade
<section id="produk-form-create" class="">
<h4 class="fw-bold py-3 mb-4">
<span class="text-muted fw-light">User /</span> Tambah Data User
</h4>
<div class="col-xxl">
<div class="card mb-4">
<div class="card-header d-flex align-items-center justify-content-between">
<h5 class="mb-0">Form Tambah Produk</h5>
</div>
<div class="card-body">
<form action="/users/store" method="POST" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-6 mb-3 text-start">
<label for="name" class="form-label">Nama User</label>
<input id="name" type="name" name="name" value="{{ old('name') }}"
class="form-control #error('name') is-invalid #enderror" required>
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-md-6 mb-3 text-start">
<label for="username" class="form-label">Username</label>
<input id="username" type="text" name="username" value="{{ old('username') }}"
class="form-control #error('username') is-invalid #enderror" required>
#error('username')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-md-6 mb-3 text-start">
<label for="email" class="form-label">Email</label>
<input id="email" name="email" value="{{ old('email') }}" type="text"
class="form-control #error('email') is-invalid #enderror" required>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-md-6 mb-3 text-start">
<label for="leveluser" class="form-label">Level User</label>
<select class="form-select #error('leveluser') is-invalid #enderror" id="leveluser"
name="level_id" required>
#foreach ($levels as $level)
<option value="{{ $level->id }}">{{ $level->level }}</option>
#endforeach
</select>
#error('level_id')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-md-6 mb-3 text-start">
<label class="form-label" for="phonenumber">Phone Number</label>
<div class="input-group input-group-merge">
<span class="input-group-text">ID (+62)</span>
<input type="text" id="phonenumber" name="phonenumber" class="form-control"
placeholder="" value="{{ old('phonenumber') }}" required>
#error('phonenumber')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-md-6 mb-3 text-start">
<label for="perusahaan" class="form-label">Perusahaan</label>
<select class="form-select #error('perusahaan_id') is-invalid #enderror" id="perusahaan_id"
name="perusahaan_id" required>
#foreach ($perusahaans as $perusahaan)
<option value="{{ $perusahaan->id }}">{{ $perusahaan->nama_perusahaan }}
</option>
#endforeach
</select>
</div>
<input type="hidden" name="password" id="password" value="12345678">
<div class="col-md-6 mb-3 text-start">
<label for="password" class="form-label">Password</label>
<p>Password default untuk user adalah
<mark><strong
class="text-warning">"12345678"</strong></mark>
mohon arahkan kepada
user untuk mengganti password demi keamanan dan kenyamanan bersama.
</p>
</div>
<div class="col-md-6 mb-3 text-start">
<label for="satker_id" class="form-label">Satuan Kerja</label>
<select id="satker_id" name="satker_id"
class="form-select #error('satker') is-invalid #enderror" required>
#foreach ($satkers->where('perusahaan_id', 1) as $satker)
<option value="{{ $satker->id }}">
{{ $satker->satker }}
</option>
#endforeach
</select>
#error('satker_id')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row">
<div class="col-sm-4 ">
<button type="submit" class="btn btn-primary"><i class="fw-icons bx bx-send"></i>
Send
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
Routes
Route::get('users', [UserController::class, 'index'])->name('users')->middleware('userlevel');
Route::get('users/{user}/edit', [UserController::class, 'edit'])->name('users.edit')->middleware('userlevel');
Route::get('users/create', [UserController::class, 'create'])->name('users.create')->middleware('userlevel');
Route::post('/users/store', [UserController::class, 'store'])->name('users.store')->middleware('userlevel');
Route::delete('users/{user}/destroy', [UserController::class, 'destroy'])->name('users.destroy')->middleware('userlevel');
Route::put('users/{user}/update', [UserController::class, 'update'])->name('users.destroy')->middleware('userlevel');
Route::post('users/action', [UserController::class, 'action']);
Success in the first-time post but get 302 found in the second time. Please help me to solve this problem.

laravel and validation with request

I cannot set correctly validation in Laravel.
Among other functions I have this in the Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Exports\RimborsiExport;
use DB;
use App\Customers;
use App\Claims;
use App\Refunds;
use App\Services;
use App\Http\Requests\RefundsPost;
use Excel;
use DataTables;
use Redirect;
use Response;
class RefundsController extends Controller
{
public function storeRefundsData(RefundsPost $request){
dd($request);
//$validated = $request->validated();
$customers = Customers::create($request->all());
return back()->with('status', 'Dati Cliente inseriti correttamente');
}
}
I have also defined a custom Request type
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RefundsPost extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$rules = [
'contr_nom' => 'required|max:255',
'contr_cog' => 'required',
'polizza' => 'required',
'email' => 'required',
'targa' => 'required',
'iban' => 'required|iban',
'int_iban' => 'required',
];
return $rules;
}
public function messages()
{
return [
'contr_nom.required' => "Il Nome Contraente e' obbligatorio",
'contr_cog.required' => "Il Cognome Contraente e' obbligatorio",
'polizza.required' => "Il numero di polizza e' obbligatorio",
'email.required' => "Una mail e' obbligatoria per le comunicazioni",
'targa.required' => "La targa e' obbligatoria",
'data_sin.required' => "La data sinistro e' obbligatoria",
'iban.required' => "Il numero IBAN e' obbligatorio",
'int_iban.required' => "L'intestatario dell' IBAN e' obbligatorio",
'dossier.required' => "Il numero di dossier e' obbligatorio",
'cliente.required' => "Il cliente e' obbligatorio",
'stato.required' => "Lo stato del rimborso e' obbligatorio",
'date_ref.required' => "La data della richiesta e' obbligatoria",
];
}
}
and i have this blade with the form inside
<div class="container-fluid">
<form method="POST" action="{{ route('storeRefundsData') }}" novalidate>
{{ csrf_field() }}
<h5 class="mb-3">Anagrafica</h5>
<div class="row">
<div class="col-md-6 mb-3">
<label for="contr_nom">Nome Contraente</label>
<input type="text" class="form-control #error('contr_nom') is-invalid #enderror" id="contr_nom" name="contr_nom" value="{{old('contr_nom')}}">
#error('contr_nom')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
<div class="col-md-6 mb-3">
<label for="contr_cog">Cognome Contraente</label>
<input type="text" class="form-control #error('contr_cog') is-invalid #enderror" id="contr_cog" name="contr_cog" value="{{old('contr_cog')}}">
#error('contr_cog')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label for="polizza">Numero Polizza <span class="text-muted"></span></label>
<input type="text" class="form-control #error('polizza') is-invalid #enderror" id="polizza" name="polizza" value="{{old('polizza')}}">
#error('polizza')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
<div class="col-md-6 mb-3">
<label for="email">Email <span class="text-muted"></span></label>
<input type="email" class="form-control #error('email') is-invalid #enderror" id="email" name="email" placeholder="tu#esempio.it" value="{{old('email')}}">
#error('email')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label for="targa">Targa veicolo</label>
<input type="text" class="form-control #error('targa') is-invalid #enderror" id="targa" name="targa" placeholder="Inserisci la targa" value="{{old('targa')}}">
#error('targa')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
</div>
<h5 class="mb-3">Dati bancari</h5>
<div class="row">
<div class="col-md-6 mb-3">
<label for="iban">IBAN <span class="text-muted"></span></label>
<input type="text" class="form-control #error('iban') is-invalid #enderror" id="iban" name="iban" placeholder="Inserisci il tuo IBAN" value="{{old('iban')}}">
#error('iban')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
<div class="col-md-6 mb-3">
<label for="int_iban">Intestatario IBAN <span class="text-muted"></span></label>
<input type="text" class="form-control #error('int_iban') is-invalid #enderror" id="int_iban" name="int_iban" placeholder="Inserisci l'intestatario dell'IBAN" value="{{old('int_iban')}}">
#error('int_iban')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
</div>
<hr class="mb-4">
<!-- <button class="btn btn-primary btn-lg btn-block" type="submit">Continue to checkout</button>-->
<input type="submit" class="btn btn-primary btn-lg btn-block" value="Salva">
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
</form>
</div>
I cannot understand why when i click on form submit button to create a new row in the db, it seems that even it doesn't enter Controller function.
If I use Request instead of custom type RefundsPost it works and store data in the db but obviously without validation.
How can i fix?
Thx a lot
Not sure if this solves your problem, but I have rewritten your functions the way I would do it. You can specify what http method the rules are for, in this case I specified the rules for POST requests.
RefundsPost -> rules:
public function rules() {
$rules = [];
switch($this->method()) {
case 'POST':
{
$rules = [
'contr_nom' => 'required|max:255',
'contr_cog' => 'required',
'polizza' => 'required',
'email' => 'required',
'targa' => 'required',
'iban' => 'required|iban',
'int_iban' => 'required',
];
}
default:
break;
}
return $rules;
}
and in the storeRefundsData function, you should use $request->validated() and use the attributes it return after validation when you proceed the insertion.
RefundsController -> storeRefundsData:
public function storeRefundsData(RefundsPost $request) {
$attributes = $request->validated();
$customers = Customers::create($attributes);
if (!($customers instanceof Customers)) {
// could not create customer
return ['result' => false];
}
$customers = $customers->fresh(); // if you need to retrieve the objects id
return ['result' => true];
}
Unfortunately, I cannot comment.
However, out of curiosity the rule iban is custom I believe right?
If so, can you try the following:
public function rules()
{
return [
'contr_nom' => ['required', 'max:255'],
'contr_cog' => ['required'],
'polizza' => ['required'],
'email' => ['required'],
'targa' => ['required'],
'iban' => ['required', new Iban],
'int_iban' => ['required'],
];
}
Of course, don't forget to import the rule class at the top:
use App\Rules\Iban;
Try it and let us know, cheers!

Laravel get a empty variable from axios.post from vuie.js module

partners from stackOverflow im making a module using laravel like backend, and vue.js by frontend, i have a form to create a new entity, but the controller dont get the values¡, plz help me to find the error. I'm going to share the code.
the routes.web
//new event from API
Route::resource('/api/events', 'EventsController', ['except' => 'show','create']);
The function in the controller EventsController.php
<?php
namespace soColfecar\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use soColfecar\Http\Requests\CreateEventRequest;
use soColfecar\Http\Requests\UpdateEventRequest;
use soColfecar\User;
use soColfecar\Change;
use soColfecar\Event;
use soColfecar\Event_type;
use Auth;
public function store(Request $request)
{
$exploded = explode(',', $request->banner);
$decoded = base64_decode($exploded[1]);
if(str_contains($exploded[0],'jpeg'))
$extension = 'jpg';
else
$extension = 'png';
$fileName = str_random().'.'.$extension;
$path = public_path().'/storage/banner/'.$fileName;
file_put_contents($path, $decoded);
Event::create([
'event' => strtoupper($request['event']),
'id_event_type' => $request['id_event_type'],
'date_init' => $request['date_init'],
'date_end' => $request['date_end'],
//'banner' => $fileName,
]);
Change::create([
'description' => 'Creo el de evento:'.$request['event'].' correctamente.',
'id_item' => 10,
'id_user' => Auth::user()->id,
]);
return redirect()->route('events.index')
->with('info', 'evento guardado con exito');
}
the method:
<form method="POST" v-on:submit.prevent="storeNewEvent">
<div class="form-group m-form__group">
<label for="eventTypeInput">Tipo de vento:</label>
<v-select :options="eventTypes" v-model="newEvent.id_event_type" id="eventTypeInput">
<template slot="option" slot-scope="option">
{{ option.label }}
</template>
</v-select>
<span v-for="error in errors" class="text-danger" :key="error.error">{{ error.city_id }}</span>
</div>
<div class="form-group m-form__group">
<label for="inputHotelName">Nombre del Evento</label>
<input type="text" class="form-control" name="inputHotelName" v-model="newEvent.event" placeholder="Nombre del Evento">
<span v-for="error in errors" class="text-danger" :key="error.error">{{ error.hotel_name }}</span>
</div>
<div class="form-group m-form__group">
<label for="date_init_imput">Fecha de inicio</label>
<input class="form-control" type="date" v-model="newEvent.date_init" value="" id="date_init_imput">
</div>
<div class="form-group m-form__group">
<label for="date_end_imput">Fecha de finalizacion</label>
<input class="form-control" type="date" v-model="newEvent.date_end" value="" id="date_end_imput">
</div>
<div class="form-group m-form__group">
<label for="customFile">Banner del Evento</label>
<div></div>
<div class="custom-file">
<input type="file" class="custom-file-input" #change="getLogo" id="customFile">
<label class="custom-file-label" for="customFile">Seleccione archivo</label>
<span v-for="error in errors" class="text-danger" :key="error.error">{{ error.logo }}</span>
</div>
</div>
<hr>
<button type="submit" class="btn btn-info waves-effect text-left">Guardar</button>
</form>
data() {
return {
changes: [],
eventTypes: [],
errors: [],
newEvent: {
event: '',
id_event_type: '',
date_init: '',
date_end: '',
banner: '',
}
}
},
storeNewEvent : function() {
var url = 'api/events';
var newEvent = this.newEvent
axios.post(url, {event: this.newEvent}).then(response => {
this.newEvent = {}
this.errors = [];
$('#new_event_modal').modal('hide');
$('.modal-backdrop').remove();
toastr.success('Se ha creado el evento con exito!')
}).catch(error => {
this.errors = error.response.data
});
},
And the error
"Too few arguments to function soColfecar\Http\Controllers\EventsController::store(), 0 passed and exactly 1 expected"
enter image description here
You need to type hint the $request so Laravel knows to fill it in ("dependency injection").
At the top of your file:
use Illuminate\Http\Request;
Then, for your function:
public function store(Request $request) {

How to Manage Accounts in the Laravel 5 FrameWork - MVC - with this code?

How to Manage Accounts in the Laravel 5 FrameWork - MVC - with this code? I got it all for a default presentation but i still get an Undefined Variable request with this code - please your answer will be appreciated:
UserController:
public function account(&$data, $request){
User::get_user(self::$data,$request);
self::$data['title'] = self::$data['title'] . 'Edit Account';
return view('forms.account', self::$data);
}
public function postAccount(AccountRequest $request){
User::edit_user($request);
return redirect('');
}
AccountRequest:
public function rules()
{
return [
'name' => 'required|min:2|max:70',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6|max:10|confirmed',
];
}
Model:
static public function get_user(&$data,$request){
$sql = "SELECT * FROM users WHERE id = ". Session::get('user_id');
$data['users'] = DB::select($sql);
}
static public function edit_user(&$data,$request) {
$id = $data['id'];
$sql = "SELECT * FROM users WHERE id = ".$id;
$getVal = DB::select($sql);
if($data['name'] || $data['password'] || $data['email']){
if($data['name']){
DB::update("UPDATE users SET name = ? WHERE id = ?",[$data['name'],$id]);
session(['user_name' => $data['name']]);
}
if($data['password']){
DB::update("UPDATE users SET password = ? WHERE id = ?",[bcrypt($data['password']),$id]);
}
if($data['email']){
DB::update("UPDATE users SET email = ? WHERE id = ?",[$data['email'],$id]);
}
}
Session::flash('sm',$request['name'] . '`s Has Been Updated');
}
Web:
Route::get('user/account', 'UserController#account');
Route::post('user/account', 'UserController#postAccount');
HTML:
#extends('master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<h1>Edit Your Account -</h1>
</div>
<div class="row" style="margin-left:30%;">
<div class="col-md-6">
<form action="" method="post">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{ $user['id'] }}">
<div class="form-group">
<label for="name"></label>
<input value="{{ $user['name'] }}" type="text" name="name"
class="form-control" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="email"></label>
<input value="{{ $user['email'] }}" type="text" name="email"
class="form-control" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="editpassword"></label>
<input type="password" name="password" class="form-control"
id="editpassword" placeholder="Edit Password">
</div>
<div class="form-group">
<label for="editpasswordconf"></label>
<input type="password" name="password_confirmation" class="form-
control" id="editpasswordconf" placeholder="Confirm New Password">
</div>
<div class="form-group text-center">
<input type="submit" name="submit" value="Update Details" class="btn
btn-primary">
</div>
</form>
</div>
</div>
</div>
#endsection
Your AccountController should look like this:
public function edit($request, Account $account){
return view('forms.account', [
'account' => $account,
'title' => 'Edit Account'
]);
}
public function update(AccountRequest $request, Account $account){
$account->update($request->all());
Session::flash('sm', $account->name . ' Has Been Updated');
return redirect()->back();
}
AccountRequest:
public function rules()
{
return [
'name' => 'required|min:2|max:70',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6|max:10|confirmed',
];
}
That is about as much code as you need for this process... please read the documentation for Eloquent https://laravel.com/docs/5.4/eloquent

Laravel PHPUnit Test Undefined Errors Variable

I would like someone to explain to me why I'm getting undefined variable errors when I run my phpunit tests from my Laravel application. I have if statements set up so that it doesn't add them by default so not sure why.
<?php
Route::auth();
Route::group(['middleware' => 'web'], function () {
Route::get('dashboard', ['as' => 'dashboard', 'uses' => 'HomeController#dashboard']);
});
<form role="form" method="POST" action="{{ url('/login') }}">
{{ csrf_field() }}
<div class="form-group form-material floating {{ $errors->has('email') ? 'has-error' : '' }}">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}"/>
<label for="email" class="floating-label">Email</label>
#if ($errors->has('email'))
<small class="help-block">{{ $errors->first('email') }}</small>
#endif
</div>
<div class="form-group form-material floating {{ $errors->has('password') ? 'has-error' : '' }}">
<input id="password" type="password" class="form-control" name="password" />
<label for="password" class="floating-label">Password</label>
#if ($errors->has('password'))
<small class="help-block pull-left">{{ $errors->first('password') }}</small>
#endif
</div>
<div class="form-group clearfix">
<div class="checkbox-custom checkbox-inline checkbox-primary checkbox-lg pull-left">
<input type="checkbox" id="inputCheckbox" name="remember">
<label for="inputCheckbox">Remember me</label>
</div>
<a class="pull-right" href="{{ url('/password/reset') }}">Forgot password?</a>
</div>
<button type="submit" class="btn btn-primary btn-block btn-lg margin-top-40">Log in</button>
</form>
<?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
class LoginTest extends TestCase
{
use WithoutMiddleware;
/** #test */
public function user_can_visit_login_page()
{
$this->visit('login');
}
/** #test */
public function user_submits_form_with_no_values_and_returns_errors()
{
$this->visit('login')
->press('Log in')
->seePageIs('login')
->see('The email field is required.')
->see('The password field is required.');
}
/** #test */
public function it_notifies_a_user_of_wrong_login_credentials()
{
$user = factory(App\User::class)->create([
'email' => 'john#example.com',
'password' => 'testpass123'
]);
$this->visit('login')
->type($user->email, 'email')
->type('notmypassword', 'password')
->press('Log in')
->seePageIs('login');
}
public function user_submits_login_form_unsuccesfully()
{
$user = factory(App\User::class)->create([
'email' => 'john#example.com',
'password' => 'testpass123'
]);
$this->visit('login')
->type($user->email, 'email')
->type($user->password, 'password')
->press('Log in')
->seePageIs('dashboard');
}
}
Errors Given
1) LoginTest::user_can_visit_login_page
A request to [http://myapp.app/login] failed. Received status code [500].
/Users/me/Projects/repositories/MyApp/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:196
/Users/me/Projects/repositories/MyApp/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:80
/Users/me/Projects/repositories/MyApp/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:61
/Users/me/Projects/repositories/MyApp/tests/LoginTest.php:13
Caused by
exception 'ErrorException' with message 'Undefined variable: errors' in /Users/me/Projects/repositories/MyApp/storage/framework/views/cca75d7b87e55429621038e76ed68becbc19bc14.php:30
Stack trace:
Remove the WithoutMiddleware trait from your test.

Resources