I have been looking for answer and tried many answer from the community here, but none of them seems to work in my case.
All was working before migration from Bootstrap to TailwindCss, now when i click logout, nothing happens.
I'm not sure if it's a javascript related issue, i hope you guys can help me with this.
auth.blade.php
<div class="hidden md:flex items-center justify-end space-x-8 md:flex-1 lg:w-0">
<span class="inline-flex rounded-md shadow-sm">
<a href="{{ route('logout') }}"
onclick="event.preventDefault(); document.getElementById('logout-form').submit();"
class="whitespace-no-wrap inline-flex items-center justify-center px-4 py-2 border border-transparent text-base leading-6 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-500 focus:outline-none focus:border-indigo-700 focus:shadow-outline-indigo active:bg-indigo-700 transition ease-in-out duration-150">
{{ __('Logout') }}
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
#csrf
</form>
</span>
</div>
Auth::routes();
Route::get('/login/applicant', 'Auth\LoginController#showApplicantLoginForm')->name('login');
Route::get('/login/employer', 'Auth\LoginController#showEmployerLoginForm');
Route::get('/register/applicant', 'Auth\RegisterController#showApplicantRegisterForm')->name('register');
Route::get('/register/employer', 'Auth\RegisterController#showEmployerRegisterForm');
// route::post('/logout', 'Auth\LoginController#logout')->name('logout');
Route::post('/login/applicant', 'Auth\LoginController#applicantLogin');
Route::post('/login/employer', 'Auth\LoginController#employerLogin');
Route::post('/register/applicant', 'Auth\RegisterController#createApplicant');
Route::post('/register/employer', 'Auth\RegisterController#createEmployer');
Auth/LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->middleware('guest:applicant')->except('logout');
$this->middleware('guest:employer')->except('logout');
}
public function showApplicantLoginForm()
{
return view('auth.login', ['url' => 'applicant']);
}
public function applicantLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
if (Auth::guard('applicant')->attempt([
'email' => $request->email,
'password' => $request->password
], $request->get('remember'))) {
return redirect()->intended('/applicant');
}
return back()->withInput($request->only('email', 'remember'));
}
public function showEmployerLoginForm()
{
return view('auth.login', ['url' => 'employer']);
}
public function employerLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
if (Auth::guard('employer')->attempt([
'email' => $request->email,
'password' => $request->password
], $request->get('remember'))) {
return redirect()->intended('/employer');
}
return back()->withInput($request->only('email', 'remember'));
}
}
Related
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
How can I make that on clicking submit button, match the users to each other, like "Secret Santa" rules? You should not be Santa of yourself, and you should not be Santa of someone who is already your Santa. After that I'm gonna filter with user->groups (Tags shown on photo)
This is my .blade.php:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('List') }}</div>
<div class="card-body">
<form action="">
#foreach($users as $user)
<div class="users-list" style="padding: 5px 0">
<h5>{{ $user->name }}</h5>
<p class="badge badge-primary">{{ $user->group }}</p>
</div>
#endforeach
<input class="btn btn-primary w-100" type="submit" value="Submit">
</form>
</div>
</div>
</div>
</div>
#endsection
And this is my RegisterController.php:
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
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', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'group' => $data['group'],
'wish' => $data['wish'],
'password' => Hash::make($data['password']),
]);
}
}
I tried to show the name of the creator of the post but I have an error
#section('content')
<div class="container" id="results">
<div class="row justify-content-center">
<div class="col-md-12" style="display: flex; flex-flow: row wrap;">
#foreach ($posts as $post)
<div class="col-md-3">
<img src="{{ asset('storage') . '/' . $post->image }}" class="w-100">
<div class="card-body">
<h5 class="card-title">{{ $post->title }}</h5>
<small>{{ Carbon\Carbon::parse($post->created_at)->diffForHumans() }}</small>
<span>PubliƩ par {{ $post->username }}</span>
<p class="card-text">{{ $post->descriptionpost }}</p>
<p class="card-text">{{ $post->price }}</p>
Voir
</div>
</div>
#endforeach
Post Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $guarded = [];
public function user()
{
return $this->belongsTo('App\User');
}
}
User Model
<?php
namespace App;
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 = [
'username', 'nom', 'prenom', 'adresse', 'ville', 'codepostale', 'datedenaissance','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 static function boot()
{
parent::boot();
static::created(function ($user) {
$user->profile()->create([
'description' => $user->username
]);
});
}
public function getRouteKeyName()
{
return 'username';
}
public function profile()
{
return $this->hasOne('App\Profile');
}
public function following()
{
return $this->belongsToMany('App\Profile');
}
public function posts()
{
return $this->hasMany('App\Post')->orderBy('created_at', 'DESC');
}
}
ProfileController
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
class ProfileController extends Controller
{
public function show(User $user)
{
$follows = (auth()->user()) ? auth()->user()->following->contains($user->profile->id) : false;
return view('profile.show', compact('user', 'follows'));
}
public function edit(User $user)
{
$this->authorize('update', $user->profile);
return view('profile.edit', compact('user'));
}
public function update(User $user)
{
$this->authorize('update', $user->profile);
$data = request()->validate([
'description' => 'required',
'image' => 'sometimes|image|max:3000'
]);
if (request('image')) {
$imagePath = request('image')->store('avatars', 'public');
$image = Image::make(public_path("/storage/{$imagePath}"))->fit(800, 800);
$image->save();
auth()->user()->profile->update(array_merge($data,
['image' => $imagePath]
));
} else {
auth()->user()->profile->update($data);
}
auth()->user()->profile->update($data);
return redirect()->route('profile.show', ['user' => $user]);
}
}
PostController
<?php
namespace App\Http\Controllers;
use App\Http\Requests\Poststore;
use App\Post;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\DB;
class PostController extends Controller
{
public function index()
{
$posts = DB::table('posts')->orderBy('created_at', 'DESC')->paginate(1000);
return view('welcome',['posts'=> $posts]);
}
public function create()
{
return view('posts.create');
}
public function store()
{
$data = request()->validate([
'title' => ['required', 'string'],
'image' => ['required', 'image'],
'price' => ['required', 'integer'],
'descriptionpost' => ['required', 'string']
]);
$imagePath = request('image')->store('uploads', 'public');
$image = Image::make(public_path("/storage/{$imagePath}"))->fit(1200, 1200);
$image->save();
auth()->user()->posts()->create([
'title' => $data['title'],
'descriptionpost' => $data['descriptionpost'],
'price' => $data['price'],
'image' => $imagePath
]);
return redirect()->route('profile.show', ['user' => auth()->user() ]);
}
public function show(Post $post)
{
return view('posts.show', compact('post'));
}
public function search(Request $request)
{
$words = $request->words;
$posts = DB::table('posts')->where('title', 'LIKE', '%$words%')->orWhere('descriptionpost', 'LIKE', '%$words%')->orderBy('created_at', 'DESC')->get();
return response()->json(['success' => true, 'posts' => $posts]);
}
}
My error:
Undefined property: stdClass::$username (View: /home/annonces/resources/views/welcome.blade.php)
Its my model post and user. Does anyone have an idea on how to resolve this? I don't know where the problem is located.
the problem is this line $post->username, you are trying to access username on post model which does not exist, first of all return the user model with the post as such
$post=post::find($id);
and in your view pass the $user to the view
#section('content')
<div class="container" id="results">
<div class="row justify-content-center">
<div class="col-md-12" style="display: flex; flex-flow: row wrap;">
#foreach ($posts as $post)
<div class="col-md-3">
<img src="{{ asset('storage') . '/' . $post->image }}" class="w-100">
<div class="card-body">
<h5 class="card-title">{{ $post->title }}</h5>
<small>{{ Carbon\Carbon::parse($post->created_at)->diffForHumans() }}</small>
<span>PubliƩ par {{ $post->user->username }}</span>
<p class="card-text">{{ $post->descriptionpost }}</p>
<p class="card-text">{{ $post->price }}</p>
<a href="{{ route('posts.show', ['post' => $post->id]) }}" class="btn btn-
primary">Voir</a>
</div>
</div>
#endforeach
I thought about adding a page, to change the profile of a user: name, surname, etc.
Bug report
File: MyAccountController.php
function: public function postAccountProfileForm(UpdateRequest $request)
the FormRequest, returns empty
What I did:
DB:
users->Profiles
File Controller: App\Http\Controllers\Auth\MyAccountController
namespace App\Http\Controllers\Auth;
use Backpack\Base\app\Http\Controllers\Auth\MyAccountController as BaseMyAccountController;
use App\Http\Requests\Auth\Account_profileRequest as StoreRequest;
use App\Http\Requests\Auth\Account_profileRequest as UpdateRequest;
use Auth;
use App\Models\Auth\Account_profile;
class MyAccountController extends BaseMyAccountController
{
/**
* Show the user a form to change his personal information.
*/
public function getAccountProfileForm()
{
$user = Auth::user();
$this->data['title'] = trans('backpack::base.my_account');
$this->data['profile'] = Account_profile::getAccount_profilebyId($user->id);
return view('backpack::auth.account.update_profile', $this->data);
}
/**
* Save the modified personal information for a user.
*/
public function postAccountProfileForm(UpdateRequest $request)
{
//var_dump($request);
//die();
//$result = $this->guard()->user()->update($request->except(['_token']));
$result = Account_profile::getAccount_profilebyId($this->guard()->user()['id'])->update($request->except(['_token']));
if ($result) {
Alert::success(trans('backpack::base.account_updated'))->flash();
} else {
Alert::error(trans('backpack::base.error_saving'))->flash();
}
return redirect()->back();
}
}
File Request: App\Http\Requests\Auth\Account_profileRequest
namespace App\Http\Requests\Auth;
use App\Http\Requests\Request;
use Illuminate\Foundation\Http\FormRequest;
class Account_profileRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
// only allow updates if the user is logged in
return backpack_auth()->check();
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
// 'name' => 'required|min:5|max:255'
'nome' => 'required|min:5|max:45',
'cognome' => 'required|min:5|max:45',
'sesso' => 'required|min:5|max:45',
'countrys_id' => 'required|numeric',
'regions_id' => 'required|numeric',
//'provinces_id' => 'required|numeric',
//'citys_id' => 'required|numeric',
'users_id' => 'required|numeric',
//'attivo' => 'required|boolean',
//'accetto_condizionigenerali' => 'required|boolean',
//'accetto_marketing' => 'required|boolean',
//'attivo_notifiche' => 'required|boolean'
//continue_13
];
}
/**
* Get the validation attributes that apply to the request.
*
* #return array
*/
public function attributes()
{
return [
//
];
}
/**
* Get the validation messages that apply to the request.
*
* #return array
*/
public function messages()
{
return [
//
];
}
}
File Models: App\Models\Auth\Account_profile
namespace App\Models\Auth;
use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\CrudTrait;
use App\Models\Profile;
class Account_profile extends Model
{
use CrudTrait;
/*
|--------------------------------------------------------------------------
| GLOBAL VARIABLES
|--------------------------------------------------------------------------
*/
/*
|--------------------------------------------------------------------------
| FUNCTIONS
|--------------------------------------------------------------------------
*/
public static function getAccount_profilebyId($id)
{
return Profile::find($id);
}
/*
|--------------------------------------------------------------------------
| RELATIONS
|--------------------------------------------------------------------------
*/
/*
|--------------------------------------------------------------------------
| SCOPES
|--------------------------------------------------------------------------
*/
/*
|--------------------------------------------------------------------------
| ACCESORS
|--------------------------------------------------------------------------
*/
/*
|--------------------------------------------------------------------------
| MUTATORS
|--------------------------------------------------------------------------
*/
}
File Route: Routes\backpack\Custom
// --------------------------
// Custom Backpack Routes
// --------------------------
// This route file is loaded automatically by Backpack\Base.
// Routes you generate using Backpack\Generators will be placed here.
Route::group([
'prefix' => config('backpack.base.route_prefix', 'admin'),
'middleware' => ['web', config('backpack.base.middleware_key', 'admin')],
'namespace' => 'App\Http\Controllers\Admin',
], function () { // custom admin routes
}); // this should be the absolute last line of this file
Route::group(
[
'namespace' => 'App\Http\Controllers\Auth',
'middleware' => ['web', config('backpack.base.middleware_key', 'admin')],
'prefix' => config('backpack.base.route_prefix'),
],
function () {
// if not otherwise configured, setup the auth routes
if (config('backpack.base.setup_auth_routes')) {
// Authentication Routes...
}
// if not otherwise configured, setup the dashboard routes
if (config('backpack.base.setup_dashboard_routes')) {
Route::get('dashboard', 'AdminController#dashboard')->name('backpack.dashboard');
Route::get('/', 'AdminController#redirect')->name('backpack');
}
// if not otherwise configured, setup the "my account" routes
if (config('backpack.base.setup_my_account_routes')) {
Route::get('edit-account-profile', 'MyAccountController#getAccountProfileForm')->name('backpack.account.profile');
Route::post('edit-account-profile', 'MyAccountController#postAccountProfileForm');
}
});
File Blade: resources\views\vendor\backpack\base\auth\account\update_profile.blade.php
#extends('backpack::layout')
#section('after_styles')
<style media="screen">
.backpack-profile-form .required::after {
content: ' *';
color: red;
}
</style>
#endsection
#section('header')
<section class="content-header">
<h1>
{{ trans('backpack::base.my_account') }}
</h1>
<ol class="breadcrumb">
<li>
{{ config('backpack.base.project_name') }}
</li>
<li>
{{ trans('backpack::base.my_account') }}
</li>
<li class="active">
{{ trans('backpack::base.update_account_info') }} Profile
</li>
</ol>
</section>
#endsection
#section('content')
<div class="row">
<div class="col-md-3">
#include('backpack::auth.account.sidemenu')
</div>
<div class="col-md-6">
<div class="box">
<div class="box-body backpack-profile-form">
{!! Form::open(array('route' => 'backpack.account.profile', 'method' => 'post')) !!}
<div class="form-group">
#php
$label = 'Nome';
$field = 'nome';
#endphp
{!! Form::label($field, $label, ['class' => 'required']) !!}
{!! Form::text($field, old($field) ? old($field) : $profile->$field, ['class' => 'form-control', 'required']) !!}
</div>
<div class="clearfix"></div>
<div class="form-group">
#php
$label = 'Cognome';
$field = 'cognome';
#endphp
{!! Form::label($field, $label, ['class' => 'required']) !!}
{!! Form::text($field, old($field) ? old($field) : $profile->$field, ['class' => 'form-control', 'required']) !!}
</div>
<div class="clearfix"></div>
<div class="form-group">
#php
$label = 'Sex';
$field = 'sesso';
#endphp
{!! Form::label($field, $label, ['class' => 'required']) !!}
{!! Form::select($field, array('M' => 'Male', 'F' => 'Female'), old($field) ? old($field) : $profile->$field, ['class' => 'form-control', 'required']) !!}
</div>
<div class="clearfix"></div>
<div class="box-footer">
#php
$field = 'id';
$label = '<span class="ladda-label"><i class="fa fa-save"></i>'.trans('backpack::base.save').'</span>';
#endphp
{!! Form::hidden($field, old($field) ? old($field) : $profile->$field) !!}
{!! Form::button($label, ['class' => 'btn btn-success', 'type' => 'submit']) !!}
<span class="ladda-label">{{ trans('backpack::base.cancel') }}</span>
</div>
{!! Form::close() !!}
</div>
</div>
</div>
</div>
#endsection
What I expected to happen:
I expect that the form is validated
What happened:
when I submit, the request returns to me empty
What I've already tried to fix it:
Backpack, Laravel, PHP, DB version:
Laravel Framework 5.7.12
"php": "^7.1.3"
"backpack/backupmanager": "^1.4"
"backpack/crud": "^3.4"
"backpack/langfilemanager": "^1.0"
"backpack/logmanager": "^2.3"
"backpack/newscrud": "^2.1"
"backpack/pagemanager": "^1.1"
"backpack/permissionmanager": "^3.12"
"backpack/settings": "^2.1"
"barryvdh/laravel-elfinder": "^0.4.1"
"fideloper/proxy": "^4.0"
"laravel/framework": "5.7.*",
"laravel/tinker": "^1.0",
"laravelcollective/html": "^5.7",
"mews/purifier": "^2.1",
"tymon/jwt-auth": "^0.5.12"
Do you told backpack to not setup auth routes so you can setup your own ?
Go ahead to config/backpack/base.php and change setup_auth_routes and setup_my_account_routes accordingly.
If you have your routes cached don't forget about php artisan route:cache
Best,
Pedro
I am learning Laravel 5 and I have wrote following code for user login. Now I am trying display validation errors messages with this code:
#if(count($errors))
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
but nothing is displaying. :(
Any idea whyerrors are not displaying, If user not enter any value and hit submit button.
Thanks.
routes.php
Route::get('/', function () {
return view('welcome');
});
Route::group(['middleware' => ['web']], function () {
Route::get('/login', ['as' => 'login', 'uses' => 'AuthController#login']);
Route::post('/handleLogin', ['as' => 'handleLogin', 'uses' => 'AuthController#handleLogin']);
Route::get('/home', ['middleware' => 'auth', 'as' => 'home', 'uses' => 'UserController#home']);
Route::get('/logout', ['as' => 'logout', 'uses' => 'AuthController#logout']);
Route::resource('user', 'UserController', ['only' => ['create', 'store']]);
});
login.blade.php
#extends('layouts.master')
#section('content')
<div class="row">
<div class="col-md-6">
<h2>Log in</h2>
<p>Hi, here you can login to your account.</p>
<br>
#if(count($errors))
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
{!! Form::open(array('route' => 'handleLogin')) !!}
<div class="form-group">
{!! Form::label('email', 'E-Mail Address') !!}
{!! Form::text('email', null, array('class' => 'form-control','placeholder' => 'example#gmail.com')) !!}
</div>
<div class="form-group">
{!! Form::label('password', 'Password') !!}
{!! Form::password('password', array('class' => 'form-control')) !!}
</div>
<div>
{!! Form::token() !!}
{!! Form::submit('Sign In' , array('class' => 'btn btn-primary')) !!}
</div>
{!! Form::close() !!}
<br>
</div>
</div>
#endsection
AuthController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\User;
class AuthController extends Controller
{
public function login()
{
return view('auth.login');
}
public function handleLogin(Request $request)
{
$this->validate($request, User::$login_validation_rules);
$data = $request->only('email', 'password');
if(\Auth::attempt($data)) {
return redirect()->intended('home');
}
return back()->withInput();
}
public function logout()
{
\Auth::logout();
return redirect()->route('login');
}
}
User.php
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public static $login_validation_rules = [
'email' => 'required|email|exists:users',
'password' => 'required'
];
}
I think you can modify your handleLogin method to send the errors to the view, something like this:
public function handleLogin(Request $request)
{
$validator=$this->validate($request, User::$login_validation_rules);
$data = $request->only('email', 'password');
if(\Auth::attempt($data)) {
return redirect()->intended('home');
}
return back()->withInput()->withErrors($validator->errors());
}
It should work
You can review the solution reading the Laravel Documentation:
https://laravel.com/docs/5.0/validation
Regards!
Why do you not use built-in register function ?
If you want you also could write your own register with Validator https://laravel.com/docs/master/validation
$validator = \Validator::make($request->all(), User::$login_validation_rules);
if($validator->passes()) {
// authenticate...
// If auth failed, add message to validator
$validator->getMessageBag()->add('password', 'Email or password invalid');
}
return redirect()->back()->withErrors($validator)->withInput();
The issue is you only handle input error, if user type invalid email or password, it not show.
laravel 5.2.*
/* app/Http/Kernel.php */
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel {
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
/* you need these two Middleware */
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
]
}
I'm adding this for those who might be have the same problem/solution that I did. I am new to Laravel (5.2) and had been experimenting with different facets of authorization and routing. At one point, my LaravelCollective HTML error bag started getting lost. After much frustration I found this -
I had created a routing group for pages requiring Authorization. I placed a forms page in that group. What I forgot to do was to remove the call to the Authorize Middleware from the controller for that page - $this->middleware('auth'); This caused the request to call for authorization twice. It did not force me to log in twice however, it did cause the session to be recreated and all previous save data was lost. I would end up with MANY session files after running the page a few times.