Laravel, can only flash error messages within controller? - php

I'm using this to flash error messages within my UserController (using Toastr);
public function update(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|max:200',
'email' => 'required|email|unique:users,email,'. Auth::id(),
'phone' => 'alpha_num|nullable|min:8',
]);
if ($validator->fails()) {
Toastr::error('Changes not saved', 'Error');
return back();
}
$user = Auth::user();
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->phone = $request->input('phone');
$user->save();
Toastr::success('Changes saved', 'OK');
return back();
}
I would like to use Form Request for my validation, but keep running into problems when trying to flash (toastr) error messages.
Do one of you have an example of toastr used with Form Request? I have read the documentation like 10 times, but can't find a solution :(
https://laravel.com/docs/5.7/validation
This used to work about a year ago, but not anymore:
# Error messages
protected function formatErrors(Validator $validator)
{
$messages = $validator->messages();
foreach ($messages->all() as $message)
{
Toastr::error($message, 'Fejl');
}
return $validator->errors()->all();
}

Use withValidator() in your form request
but I am using toaster package from yoeunes/toastr
public function withValidator($validator)
{
$messages = $validator->messages();
foreach ($messages->all() as $message)
{
toastr()->error ( $message, 'Error');
}
return $validator->errors()->all();
}
It works for me in Laravel 7.x
Try that, thanks!

Related

I can't change error message in my project

I have a Laravel 8 project. I want to change magic auth error message. And I did updated my code like this.
'This code has already been used' I replaced this message with this in the context of the code 'You will get a link in your email inbox every time you need to log in or register. Keep in mind that each link can only be used once.'
OLD AuthController.php
public function magicauth(Request $request)
{
$auth = app('firebase.auth');
$email = $request->email;
$oobCode = $request->oobCode;
$exits = User::where('email', $email)->first();
if(!is_null($exits))
{
if(is_null($exits->firebaseUserId))
{
$fUser = $auth->createUser([
'email' => $exits->email,
'emailVerified' => true,
'displayName' => $exits->name,
'password' => ($exits->email . $exits->id),
]);
$firebaseID = $fUser->uid;
$exits->update([
'firebaseUserId' => $firebaseID
]);
}
}
try
{
$result = $auth->signInWithEmailAndOobCode($email, $oobCode);
$firebaseID = $result->firebaseUserId();
$user = User::where('firebaseUserId', $firebaseID)->first();
if(is_null($user))
{
return view('auth.messages', ['message' => 'User not found']);
}
if($user->role_id != 3)
{
return view('auth.messages', ['message' => 'User is not creator']);
}
Auth::login($user);
return redirect()->route('home');
} catch (\Exception $e) {
return view('auth.messages', ['message' => 'This code has already been used.']);
}
return redirect()->route('login');
}
NEW AuthController.php
public function magicauth(Request $request)
{
$auth = app('firebase.auth');
$email = $request->email;
$oobCode = $request->oobCode;
$exits = User::where('email', $email)->first();
if(!is_null($exits))
{
if(is_null($exits->firebaseUserId))
{
$fUser = $auth->createUser([
'email' => $exits->email,
'emailVerified' => true,
'displayName' => $exits->name,
'password' => ($exits->email . $exits->id),
]);
$firebaseID = $fUser->uid;
$exits->update([
'firebaseUserId' => $firebaseID
]);
}
}
try
{
$result = $auth->signInWithEmailAndOobCode($email, $oobCode);
$firebaseID = $result->firebaseUserId();
$user = User::where('firebaseUserId', $firebaseID)->first();
if(is_null($user))
{
return view('auth.messages', ['message' => 'User not found']);
}
if($user->role_id != 3)
{
return view('auth.messages', ['message' => 'User is not creator']);
}
Auth::login($user);
return redirect()->route('home');
} catch (\Exception $e) {
return view('auth.messages', ['message' => 'You will get a link in your email inbox every time you need to log in or register. Keep in mind that each link can only be used once.']);
}
return redirect()->route('login');
}
But when I try now, I see that the message has not changed. How can I fix this?
Please follow below steps:
If you haven't done it yet, delete or rename the old AuthController class, use only new one, with new message.
Make sure routes going to the methods in the new controller
Run composer dump-autoload.
If the problem still persist I'd check whether some kind of cache mechanism is enabled in php, like opcache.

Call to undefined function App\Http\Controllers\Auth\array_get() in laravel 6.16

in my controller I create a function to validate user and notify via mail
protected function register(Request $request)
{
/** #var User $user */
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
try {
$validatedData['password'] = bcrypt(array_get($validatedData, 'password'));
$validatedData['activation_code'] = str_random(30).time();
$user = app(User::class)->create($validatedData);
} catch (\Exception $exception) {
logger()->error($exception);
return redirect()->back()->with('message', 'Unable to create new user.');
}
$user->notify(new UserRegisteredSuccessfully($user));
return redirect()->back()->with('message', 'Successfully created a new account. Please check your email and activate your account.');
}
For some reason, I keep getting this error
Call to undefined function App\Http\Controllers\Auth\array_get()
Can someone please teach me how to fix this error ?
Much appreciated in advance.
Use \Arr::get() instead of array_get() in laravel 6. array_get() deprecated in Laravel 6.x. So check this:
protected function register(Request $request)
{
/** #var User $user */
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
try {
$validatedData['password'] = bcrypt(\Arr::get($validatedData, 'password'));
$validatedData['activation_code'] = \Str::random(30).time();
$user = app(User::class)->create($validatedData);
} catch (\Exception $exception) {
logger()->error($exception);
return redirect()->back()->with('message', 'Unable to create new user.');
}
$user->notify(new UserRegisteredSuccessfully($user));
return redirect()->back()->with('message', 'Successfully created a new account. Please check your email and activate your account.');
}

How to broadcast a message in Laravel

I'm trying to broadcast a message or a notification to all the users after the store function of my controller is successfull.
public function store(Request $request,$id)
{
if(Auth::check()){
$permit = Permit::where('id',$id)->first();
if ($permit)
{
$request->validate([
'invoice_no' => 'required|string|max:255',
]);
$invoice = Invoice::insert([
'invoice_no' => $request->input('invoice_no'),
'invoice_date' => $request->input('invoice_date'),
'permit_id' => $permit->id,
'created_at' => Carbon::now(),
]);
if($invoice){
$permit->invoiced = 1;
$permit->save();
$users = User::where('user_type','superadmin')->get();
$message = "Permit number ".$permit->permit_no." invoiced successful!";
foreach ($users as $user) {
// Need to implement a method here to notify all users
}
return redirect()->route('invoices.index')
->with('success' , 'successFull');
}
}
return back()->withInput()->with('errors', 'Error Exists!');
}
}
So $message is the message I'm trying to notify all users.
I want to use something like bootstrap-notify package to show the message. How can this be achieved? I had done some tutorials but it uses Vue.js and I dont want to jump into Vue.js for now. So any other solutions please reply.

User Roles in Laravel

I want to implement user roles for my controller. When the user is admin or master it works, but when the user is a client it doesn't, and I receive a 205 http response.
This code works nicely in my localhost but it doesn't so in my host.
public function store(Request $request)
{
$validation = Validator::make($request->all(), [
'name' => 'required|string',
'imageone'=> 'required|string'
]);
if ($validation->fails())
{
return response()->json('Fails',404);
}
$user = JWTAuth::parseToken()->authenticate();
if ($user->roles=='admin'||$user->roles=='master') {
$name= $request->input('name');
$imageone = $request->input('imageone');
$cate=new categoryi();
$cate->name=$name;
$cate->imageone=$imageone;
if ($cate->save())
{
return response()->json($cate,202);
}
}
return response()->json('Fails',500);
}

For Laravel, How to return a response to client in a inner function

I'm building an api using laravel, the issue is when the client requests my api by calling create() function, and the create()function will call a getValidatedData() function which I want to return validation errors to the client if validation fails or return the validated data to insert database if validation passes, my getValidatedData function is like below so far
protected function getValidatedData(array $data)
{
// don't format this class since the rule:in should avoid space
$validator = Validator::make($data, [
'ID' => 'required',
'weight' => 'required',
]);
if ($validator->fails()) {
exit(Response::make(['message' => 'validation fails', 'errors' => $validator->errors()]));
}
return $data;
}
I don't think exit() is a good way to return the errors message to clients. are there any other ways I can return the laravel Response to clients directly in an inner function. use throwing Exception?
This was what worked for me in Laravel 5.4
protected function innerFunction()
{
$params = [
'error' => 'inner_error_code',
'error_description' => 'inner error full description'
];
response()->json($params, 503)->send();
}
What you can do is using send method, so you can use:
if ($validator->fails()) {
Response::make(['message' => 'validation fails', 'errors' => $validator->errors()])->send();
}
but be aware this is not the best solution, better would be for example throwing exception with those data and adding handling it in Handler class.
EDIT
As sample of usage:
public function index()
{
$this->xxx();
}
protected function xxx()
{
\Response::make(['message' => 'validation fails', 'errors' => ['b']])->send();
dd('xxx');
}
assuming that index method is method in controller you will get as response json and dd('xxx'); won't be executed
You can use this method
public static function Validate($request ,$rolse)
{
// validation data
$validator = Validator::make($request->all(),$rolse);
$errors = $validator->getMessageBag()->toArray();
$first_error = array_key_first($errors);
if (count($errors) > 0)
return 'invalid input params , ' . $errors[$first_error][0];
return false;
}
in controller :
$validate = ValidationHelper::Validate($request,
['title' => 'required']);
if ($validate)
return response()->json(['message' =>'validation fails' , 'error'=> $validate], 403);

Categories