How to broadcast a message in Laravel - php

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.

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.');
}

Laravel, can only flash error messages within controller?

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!

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);
}

updating value in laravel using api call

I have been trying to update the handicap score using a post request. But I seem to get an error saying : creating default object from empty value.
Code :
public function handicap(Request $request)
{
$user = Auth::user();
$rules = array(
'handicap' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails())
{
return response()->json(['msg' => 'Failed to update Handicap score!'], 200);
}
else {
if(Handicap::where('user_id', '=', $user->id)->exists())
{
$handicap = Handicap::find($user->id);
$handicap->user_id = $user->id;
$handicap->handicap = $request->input('handicap');
$handicap->save();
return response()->json(['msg' => 'You have successfully updated your handicap score!'], 200);
}
else
{
$handicap = new Handicap;
$handicap->user_id = $user->id;
$handicap->handicap = $request->input('handicap');
$handicap->save();
return response()->json(['msg' => 'You have added your handicap score successfully!'], 200);
}
}
}
If user does not exist in Handicap table then the else block code runs and creates a handicap score for the user else the if block needs to execute and update the score. I tried many alternatives but dont seem to get it working. Dont know what am I doing wrong.
I checked the $user, $handicap variables using return. those variables have the info that I need to add to the table. Its just that Its not updating.
Your problem probably comes from the line you have Handicap::find($user->id). Obviously it's null, because such model was not found, even though your if statement returns true.
In your if statement you have where('user_id' , '=', $user->id), but you are using Handicap::find($user->id) which is basically Handicap::where('id', '=', $user->id)->first().
Try changing it to:
$handicap = Handicap::where('users_id', '=', $user->id)->first();
You may give this a try:
public function handicap(Request $request)
{
$validator = Validator::make(Input::all(), [
'handicap' => 'required'
]);
// process the login
if ($validator->fails()) {
return response()->json(['msg' => 'Failed to update Handicap score!'], 200);
}
$handicap = Handicap::firstOrNew([
'user_id' => $request->user()->id;
]);
$handicap->user_id = $request->user()->id;
$handicap->handicap = $request->handicap;
$handicap->save();
return response()->json(['msg' => 'You have successfully updated your handicap score!'], 200);
}

Categories