Where am I making a mistake in if else statement? - laravel

I can't return a toast error message. Where am I making a mistake? Message returns when successful.
My code is as follows:
public function store(Request $request)
{
$validated = $request->validate([
'category_name' => 'required|unique:categories|max:50',
]);
$data = array();
$data['category_name'] = $request->category_name;
$save = DB::table('categories')->insert($data);
if ($save) {
Toastr::success('Post Successfully Saved :)', 'Success');
return redirect()->route('admin.category');
} else {
Toastr::error('Error :)', 'Error');
return redirect()->route('admin.category');
}
}

Try the following:
public function store(Request $request)
{
$validated = $request->validate([
'category_name' => 'required|unique:categories|max:50',
]);
$data = array();
$data['category_name'] = $request->category_name;
$save = DB::table('categories')->insert($data);
if (!$save) {
Toastr::error('Error :)', 'Error');
return redirect()->route('admin.category');
} else {
Toastr::success('Post Successfully Saved :)', 'Success');
return redirect()->route('admin.category');
}
}

You can try this code.. You can use ->fails() function to check the inputs
public function store(Request $request)
{
$validated = $request->validate([
'category_name' => 'required|unique:categories|max:50',
]);
if($validated->fails()){
Toastr::error('Error :)','Error');
return redirect()->route('admin.category');
}
$data=$request->only(['category_name']);
$save = DB::table('categories')->insert($data);
Toastr::success('Post Successfully Saved :)','Success');
return redirect()->route('admin.category');
}

I found the solution . I created a validator myself
public function store(Request $request)
{
$validated = Validator::make($request->all(), [
'category_name' => 'required|unique:categories|max:50',
]);
$notificationerror=array(
'messege'=>'Category Added Error',
'alert-type'=>'error',
'positionClass' =>'toast-top-right'
);
if($validated->fails()){
return redirect()->route('admin.category')->with($notificationerror);
}
$data=array();
$data['category_name']=$request->category_name;
DB::table('categories')->insert($data);
$notification=array(
'messege'=>'Category Added Successfully',
'alert-type'=>'success',
);
return redirect()->route('admin.category')->with($notification);
}

Related

Laravel couldn't verify created user for login

in this simple code i created function to created users into database, after created them i can't verify username and password there and i get false
public function store(RequestUsers $request)
{
$user = User::create(array_merge($request->all(), ['username'=>'testtest', 'password' => bcrypt('testtest')]));
if ($user->id) {
dd(auth()->validate(['username'=>'testtest','password'=>$user->password]));
} else {
}
}
what's problem of my code which i can't verify created user?
full my login controller:
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/';
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function login(Request $request)
{
$this->validateLogin($request);
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if (auth()->validate($request->only('username','password'))) {
$user = User::whereUsername($request->username)->first();
if ($user->lock) {
$request->session()->flash('error',__('message.your_account_locked'));
return view('layouts.backend.pages.auth.account.locked_account');
}elseif (!$user->active) {
$checkActivationCode = $user->activationCode()->where('expire', '>=', Carbon::now())->latest()->first();
if ($checkActivationCode != null) {
if ($checkActivationCode->expire > Carbon::now()) {
$this->incrementLoginAttempts($request);
$request->session()->flash('error',__('message.please_active_your_account'));
return view('layouts.backend.pages.auth.account.active_account');
}
}else{
return redirect()->to('/page/userAccountActivation/create');
}
}
}
if ($this->attemptLogin($request)) {
//dd('aaaaaa');
return $this->sendLoginResponse($request);
}
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
public function redirectToProvider()
{
return Socialite::driver('google')->redirect();
}
public function handleProviderCallback()
{
$socialUser = Socialite::driver('google')->stateless()->user();
$user = User::whereEmail($socialUser->getEmail())->first();
//dd($socialUser->getAvatar());
if (!$user) {
$data = [
'name' => $socialUser->getName(),
'email' => $socialUser->getEmail(),
'avatar' => str_replace('sz=50', 'sz=150', $socialUser->getAvatar()),
'mobileNumber' => '',
'loginType'=>'google',
'password' => bcrypt($socialUser->getId()),
];
//dd($data);
$user = User::create($data);
}
if ($user->active == 0) {
$user->update([
'active' => 1
]);
}
auth()->loginUsingId($user->id);
return redirect('/system/UserLoginWithGoogle');
}
public function show()
{
return view('auth.login');
}
protected function validateLogin(Request $request)
{
$this->validate($request, [
'username' => 'required|string',
'password' => 'required|string',
'g-recaptcha-response', 'recaptcha'
]);
}
}
dd(auth()->validate(['username'=>'testtest','password'=>$user->password]));
Validate method expects the array to hold plain text value for the password. $user->password would be the hashed value, and it will always return false for that reason.
Changing that to:
dd(auth()->validate(['username'=>'testtest','password'=>'testtest']));
should yield the desired output.

how to make admin forget password functionality in laravel?

I want to create a forgot password functionality of admin panel but, now I am using the custom admin login functionality in my AdminController. how can I create a forgot password functionality with a token for the admin panel ?
MY AdminController Code Here ...
login Method
public function login(Request $request)
{
if($request->isMethod('post')) {
$data = $request->input();
$adminCount = Admin::where([
'username' => $data['username']
'password'=> md5($data['password']),
'status'=> 1
])->count();
if($adminCount > 0){
//echo "Success"; die;
Session::put('adminSession', $data['username']);
return redirect('/admin/dashboard');
}else{
//echo "failed"; die;
return redirect('/admin')->with('flash_message_error','Invalid Username or Password');
}
}
return view('admin.admin_login');
}
Reset Method
public function reset(ResetPasswordRequest $request)
{
$credentials = $request->only(
'email', 'password', 'password_confirmation', 'token'
);
$response = Password::reset($credentials, function ($user, $password) {
$this->resetPassword($user, $password);
});
switch ($response) {
case Password::PASSWORD_RESET:
return redirect($this->redirectPath())->with('status', trans($response));
default:
return redirect()->back()
->withInput($request->only('email'))
->withErrors(['email' => trans($response)]);
}
}
You should try this:
public function reset(ResetPasswordRequest $request)
{
$credentials = $request->only(
'email', 'password', 'password_confirmation', 'token'
);
$response = Password::reset($credentials, function ($user, $password) {
$this->resetPassword($user, $password);
});
switch ($response) {
case Password::PASSWORD_RESET:
return redirect($this->redirectPath())->with('status', trans($response));
default:
return redirect()->back()
->withInput($request->only('email'))
->withErrors(['email' => trans($response)]);
}
}

How to display array data after store & email sent?

UPDATE
I have contact form. it works good. I would like to display $data array at
final page which is admintemp.blade.php.
I can display $data array at one step before final page. but I would like to display those at last page too.
I thoguht just add this
return view('mail.complete', ['data' => $data]);
is fine. but I got this error
Invalid argument supplied for foreach()
Could you teach me right way please?
Here is my code
/*
*confirm page
*/
public function confirm(Request $request)
{
$rules = [
'orderer' => 'required'
];
$this->validate($request, $rules);
$data = $request->all();
$request->session()->put('data',$data);
return view('mail.confirm', compact("data"));
}
/*
* complete page
*/
public function complete(Request $request)
{
$data = $request->session()->pull('data');
$token = array_shift($data);
$Contact = Contact::create($data);
$data = session()->regenerateToken();
return view('mail.complete', ['data' => $data]);
}
UPDATES 2
complete.blade.php
#foreach ($data as $val)
{{ $val->id }}
{{ $val->tel }}
#endforeach
for example you have two step form
first step post method:
public function postCreateStep1(Request $request)
{
$validatedData = $request->validate([
'name' => 'required',
]);
if (empty($request->session()->get('contact'))) {
$contact = new Contact();
$contact->fill($validatedData);
$request->session()->put('contact', $contact);
} else {
$contact = $request->session()->get('contact');
$contact->fill($validatedData);
$request->session()->put('contact', $contact);
}
return redirect('/create-step2');
}
second step post method:
public function postCreateStep2(Request $request)
{
$validatedData = $request->validate([
'family' => 'required',
]);
if (empty($request->session()->get('contact'))) {
$contact = new Contact();
$contact->fill($validatedData);
$request->session()->put('contact', $contact);
} else {
$contact = $request->session()->get('contact');
$contact->fill($validatedData);
$request->session()->put('contact', $contact);
}
$created_contact = Contact::create([
'name' => $contact->name,
'family' => $contact->family,
]);
// Do whatever you want with $created_contact
return redirect('/');
}

Laravel 4 Authentication does not work and gives NO ERROR

I have been searching for solutions and changing my code back and forth but nothing worked for me and I honestly have given up hope to fix it by myself.
It stays on the same page and does not Redirect::to('test2'), but stays in the same page and when I remove the else { return Redirect::to('login'), it gives me a blank page.
Any help would be extremely appreciated.
This is my user model file:
protected $fillable=['email', 'password'];
protected $table = 'users';
protected $hidden = array('password', 'remember_token');
protected $primaryKey = 'id';
public static $rules = array(
'email' => 'required|email',
'password' => 'required',
);
public function getAuthIdentifier()
{
return $this->getKey();
}
public function getAuthPassword()
{
return $this->password;
}
public function getReminderEmail()
{
return $this->email;
}
This is my routing functions:
Route::get('/login', function(){
return View::make('login');
});
Route::post('/login', function(){
$validator = Validator::make(Input::all(), User::$rules);
if ($validator->fails()) {
return Redirect::to('login')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
$userData = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
if (Auth::attempt($userData)) {
return Redirect::to('test2');
echo 'SUCCESS!';
} else {
return Redirect::to('login');
}
}
I have been struggling around with the hash at beginning.
1. If the length of your password column isn't 60 then it wouldn't allow you to login.
2. Before logging via Auth::attempt() instead try to fetch the data of the user using his username
and then compare the password using Hash::check()
try something this
Route::post('/login', function(){
$validator = Validator::make(Input::all(), User::$rules);
if ($validator->fails()) {
return Redirect::to('login')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
$email=Input::get('email');
$user=User::where('email','=',$email)->first();
$bool=Hash::check('your password for the email',$user->password);
if(bool)
{
if (Auth::attempt(Input::only('email','password')))
{
return Redirect::to('test2');
echo 'SUCCESS!';
}else{
return Redirect::to('login');
}
}else{
return echo 'password didn't matche';
}
}

Laravel Testing User::store() with phpunit

I'm learning both Laravel and UnitTesting at the moment, so this may be a stupid question.
I'm getting stuck on how to best test the controller function below:
UserController:
public function store()
{
$input = Input::all();
$user = new User($input);
if( ! $user->save()){
return Redirect::back()->withInput()->withErrors($user->getErrors());
}
return Redirect::to('/user');
}
here's the test as I have it so far:
/**
* #dataProvider providerTestUserStoreAddsUsersCorrectly
*/
public function testUserStoreAddsUsersCorrectly($first_name, $last_name, $email, $password)
{
$response = $this->call('POST', 'user', array('first_name'=>$first_name, 'last_name'=>$last_name, 'email'=>$email, 'password'=>$password));
}
public function providerTestUserStoreAddsUsersCorrectly(){
return array(
array("FirstName", "LastName", "Email#add.com", "pass1234")
);
}
This is actually working and adding the user to the db correctly, but I'm not sure how to test the output / what assertions to use as the response should be to add the user to the db and to redirect to the /user page.
How do I finish this test?
If you need to check success status then you can simply send status code from your controller
and check status in test
public function store()
{
$input = Input::all();
$user = new User($input);
if( !$user->save() ){
return array("status"=>'failed');
}
return array("status"=>'success');
}
public function testUserStoreAddsUsersCorrectly($first_name, $last_name, $email, $password)
{
$requested_arr = [
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
'password' => $password
];
$response = $this->call('POST', 'user', $requested_arr);
$data = json_decode($response ->getContent(), true);
if ($data['status']) {
$this->assertTrue(true);
} else {
$this->assertTrue(false);
}
}

Resources