Laravel Does Not Sent Anything to Pusher - php

Pusher did not receive any data from my laravel project. in the debug console still waiting for events
and i didn't get any error message
My Controller
public function store(Request $request){
$user = Auth::user();
$message = $user->messages()->create([
'message' => $request->message,
'room_id' => $request->room_id
]);
broadcast(new MessageSent(auth()->user(), $message))->toOthers();
return response()->json([
'success' => true,
'message' => 'Chat Has Been Added',
], 200);
}
My Event
public function __construct(User $user, GrupChat $grupchat)
{
$this->user = $user;
$this->grupchat = $grupchat;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('chat');
}
}
And The channels.php
Broadcast::channel('chat', function ($user) {
return Auth::check();
});

Related

Laravel Socialite: This authorization code has been used (Facebook)

Description: I have implemented the laravel socialite stateless, because I am using Laravel as a backend app with REST APIs and my frontend is in Angular. I get the correct redirect URL, however, when I enter my Facebook credentials and agree to proceed with the application I get redirected to my site with the following issue:
Client error: `POST https://graph.facebook.com/v3.3/oauth/access_token` resulted in a `400 Bad Request` response: {"error":{"message":"This authorization code has been used.","type":"OAuthException","code":100,"error_subcode":36009,"f (truncated...)
Here are the routes in my api.php
Route::get('/auth/redirect/{provider}', [AuthController::class, 'redirectToProvider'])
->where('provider', '[A-Za-z]+');
Route::get('/auth/{provider}/callback', [AuthController::class, 'handleProviderCallback'])
->where('provider', '[A-Za-z]+');
And the following functions in my controller AuthController.php
/**
* #param $provider
* #return JsonResponse
*/
public function redirectToProvider($provider): JsonResponse
{
$response = $this->authService->redirectToProvider($provider);
return response()->json($response);
}
/**
* #param $provider
* #param Request $request
* #return JsonResponse
* #throws \App\Exceptions\Custom\CustomValidationException
*/
public function handleProviderCallback($provider, Request $request): JsonResponse
{
ValidationUtils::validate($request->all(), [
'code' => 'required',
]);
$response = $this->authService->handleProviderCallback($provider);
return response()->json($response);
}
And this is where it resolves in the AuthServiceImpl.php
/**
* #param $provider
* #return array[]
*/
public function redirectToProvider($provider): array
{
if (!in_array($provider, self::PROVIDERS)) {
throw new CustomNotFoundException(trans('errors.not_found.provider'));
}
$success['provider_redirect'] = Socialite::driver($provider)->stateless()->redirect()->getTargetUrl();
return [
'data' => $success
];
}
/**
* #param $provider
* #return array[]|void
*/
public function handleProviderCallback($provider)
{
if (!in_array($provider, self::PROVIDERS)) {
throw new CustomNotFoundException(trans('errors.not_found.provider'));
}
try {
$providerUser = Socialite::driver($provider)->stateless()->user();
if ($providerUser) {
$user = $this->socialAccountsService->findOrCreate($providerUser, $provider);
$user->markEmailAsVerified();
$token = $user->createToken(env('API_AUTH_TOKEN_PASSPORT_SOCIAL'))->accessToken;
return [
'data' => [
'tokens' => [
'token_type' => 'Bearer',
'expires_in' => 5400,
'access_token' => $token
],
'user' => new UserResource($user)
],
'message' => trans('auth.login')
];
}
} catch (\Exception $e) {
throw new CustomUnauthorizedException($e->getMessage());
}
}
You can try it yourself by logging in with Facebook on the following link: https://afillix.common.mk/login

Laravel Spatie Permissions - There is no role named `student`

I'm using the Laravel Permissions package by Spatie with Laravel Breeze. I created two registration forms for two types of users: "Student" and the other for "Instructor." When I create an account as "Student,", it displays the following error message.
There is no role named student.
RegisteredUserController
class RegisteredUserController extends Controller
{
/**
* Display the registration view for student.
*
* #return \Illuminate\View\View
*/
public function createStudent()
{
$role = Role::create(['name' => 'student']);
return view('auth.student.student-space', compact('student'));
}
/**
* Display the registration view for instructor.
*
* #return \Illuminate\View\View
*/
public function createInstructor()
{
$role = Role::create(['name' => 'instructor']);
return view('auth.instructor.instructor-space', compact('role'));
}
/**
* Handle an incoming registration request.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*
* #throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|confirmed|min:8',
]);
Auth::login($user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]));
$user->assignRole('student', 'instructor');
$user->save();
// Check if the "Student" has the correct role
if ($user->hasRole('student')) {
return redirect()->intended('/student/dashboard');
}
// Check if the "Instructor" has the correct role
if ($user->hasRole('instructor')) {
return redirect()->intended('/instructor/dashboard');
}
event(new Registered($user));
}
}
AuthenticatedSessionController
public function store(LoginRequest $request)
{
$request->authenticate();
$request->session()->regenerate();
if(auth()->check() && auth()->user()->hasRole('student')) {
return redirect()->intended('/student/dashboard');
}
if(auth()->check() && auth()->user()->hasRole('instructor')) {
return redirect()->intended('/instructor/dashboard');
}
// return redirect(RouteServiceProvider::HOME);
}
routes/auth.php
Route::get('/student-space',
[RegisteredUserController::class, 'createStudent'])
->middleware('guest')->name('student-space');
Route::post('/student-space',
[RegisteredUserController::class, 'store'])
->middleware('guest');
Route::get('/instructor-space',
[RegisteredUserController::class, 'createInstructor'])
->middleware('guest')->name('instructor-space');
Route::post('/instructor-space',
[RegisteredUserController::class, 'store'])
->middleware('guest');

Laravel routing issues

I'm trying to make a get request to rest api, route bellow:
Route::group(
['middleware' => 'api'],
function() {
Route::get('users', 'UserApiController#index')->name('api.user.list');
Route::get('users/{user}', 'UserApiController#show')->name('api.user.user');
Route::post('users', 'UserApiController#store')->name('api.user.create');
Route::put('users/{user}', 'UserApiController#update')->name('api.user.update');
Route::delete('users/{user}', 'UserApiController#destroy')->name('api.user.delete');
Route::patch('users/{user}/credentials', 'UserApiController#setCredentials')->name('api.user.set_credentials');
Route::get('users/credentials', 'UserApiController#findByCredentials')->name('api.user.find_by.credentials');
Route::get('users/email/{email}', 'UserApiController#findByEmail')->name('api.user.find_by.email');
Route::get('users/phone/{phone}','UserApiController#findByPhone')->name('api.user.find_by.phone');
});
Controller
<?php
namespace App\Http\Controllers;
use App\Http\Requests\CreateUserRequest;
use App\Http\Requests\SetCredentialsRequest;
use App\Http\Requests\UpdateUserRequest;
use App\Models\User;
use App\Models\UserEmail;
use App\Models\UserPhone;
use Illuminate\Http\JsonResponse;
use App\Http\Resources\User as UserResource;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class UserApiController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(): JsonResponse
{
return response()->json(
['data' => UserResource::collection(User::all())],
200
);
}
/**
* Display the specified resource.
*
* #param \App\Models\User $user
* #return \Illuminate\Http\Response
*/
public function show(User $user): JsonResponse
{
return response()->json(
['data' => new UserResource($user)],
200
);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(CreateUserRequest $request): JsonResponse
{
try {
DB::beginTransaction();
$user = (new User())
->create(
$request->only(['uuid', 'first_name', 'last_name'])
);
$email = $request->get('email');
$user->emails()->save(
new UserEmail(['email' => $email])
);
DB::commit();
} catch (\Throwable $exception) {
DB::rollBack();
return response()
->json(['error' => $exception->getMessage()], 500);
}
return response()->json(
['data' => new UserResource($user)],
201
);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\User $user
* #return \Illuminate\Http\Response
*/
public function update(UpdateUserRequest $request, User $user): JsonResponse
{
$user->update($request->only(['username', 'password', 'first_name', 'last_name']));
return response()->json(
['data' => new UserResource($user)],
200
);
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\User $user
* #return \Illuminate\Http\Response
*/
public function destroy(User $user): JsonResponse
{
$user->delete();
return response()->json(
null,
204
);
}
public function setCredentials(SetCredentialsRequest $request, User $user)
{
$user->update([
'username' => $request->get('username'),
'password' => \password_hash($request->get('password'), \PASSWORD_BCRYPT),
]);
return response()->json(
['data' => new UserResource($user)],
200
);
}
public function findByCredentials(Request $request)
{
}
public function findByEmail(string $email)
{
$user = UserEmail::all()
->where('email', '=', $email)
->first()
->user()
->getResults();
return response()->json(
['data' => new UserResource($user)],
200
);
}
public function findByPhone(string $phone)
{
$user = UserPhone::all()
->where('phone', '=', $phone)
->first()
->user()
->getResults();
return response()->json(
['data' => new UserResource($user)],
200
);
}
}
Got an error:
No query results for model [App\\Models\\User] credentials
As I understand,laravel is attempting to find credentials field in User model to resolve it.
Controller method is never handled.
If I use Route::post - everything is ok.
How to disable "auto-finding", so I could get control in the controller?
Changing the possion of the route solved the problem:
Route::group(
['middleware' => 'api'],
function() {
Route::get('users/credentials', 'UserApiController#findByCredentials')->name('api.user.find_by.credentials');
Route::get('users', 'UserApiController#index')->name('api.user.list');
Route::get('users/{user}', 'UserApiController#show')->name('api.user.user');
Route::post('users', 'UserApiController#store')->name('api.user.create');
Route::put('users/{user}', 'UserApiController#update')->name('api.user.update');
Route::delete('users/{user}', 'UserApiController#destroy')->name('api.user.delete');
Route::patch('users/{user}/credentials', 'UserApiController#setCredentials')->name('api.user.set_credentials');
Route::get('users/email/{email}', 'UserApiController#findByEmail')->name('api.user.find_by.email');
Route::get('users/phone/{phone}','UserApiController#findByPhone')->name('api.user.find_by.phone');
});

PusherBroadcaster error. Laravel 6 - How to Fix?

I have Laravel 6 and use pusher as a broadcast event. But I get this error (see screenshot)
the error
\Illuminate\Broadcasting\Broadcasters\PusherBroadcaster.php:121
screenshot stacktrace error
here is my controller:
public function sendMessage(Request $request)
{
//validate incoming request
$this->validate($request, [
'message' => 'required|string'
]);
try {
$iam = Auth::user();
$message = $iam->family->messages()->create([
'message' => $request->input('message'),
'id_user' => $iam->id
]);
event(new ChatSubmitted('$message'));
//return successful response
return response()->json(['messages' => $request->all(), 'message' => 'Send Message Succesfully'], 200);
} catch (\Exception $e) {dd($e);
//return error message
return response()->json(['message' => 'Send Message Failed!'], 409);
}
}
and here is my event:
class ChatSubmitted implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct($message)
{
$this->message = $message;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('my-channel');
}
}
the routes of api:
Route::get('messages', 'ChatsController#fetchMessages');
Route::post('messages/create', 'ChatsController#sendMessage');

Laravel Registration Redirect based on Roles

I have a vendor and customer in login, It works fine and redirects to the vendor or customer dashboard but how can I do the same after registration?
Register Controller
protected $redirectTo = '/';
Login Controller
<?php
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6',
]);
if (Auth::guard('web')->attempt(['email' => $request->email, 'password' => $request->password, 'active' => 1, 'role_id' => 2], $request->remember)) {
return redirect()->intended(route('customer.dashboard'));
} elseif (Auth::guard('web')->attempt(['email' => $request->email, 'password' => $request->password, 'active' => 1, 'role_id' => 1], $request->remember)) {
return redirect()->intended(route('vendor.dashboard'));
}
return redirect()->back()->withInput($request->only('email', 'remember'));
}
Not sure which version you are using I'm posting my answer for Laravel 5.7+
After registration Laravel call this method:
// Auth\RegisterController
/**
* The user has been registered.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function registered(Request $request, $user)
{
// Assign role to $user. Then you can add condition.
if($user->hasRole('admin'){
return redirect()->route('xxx');
}
return redirect()->route('default');
}
Hope it can help you.
Good Luck!
You can try something like this instead
<?php
public function login (Request $request) {
$this->validate($request,[
'email'=>'required|email',
'password'=>'required|min:6',
]);
$authenticated = Auth::guard('web')->attempt(['email'=>$request->email,'password'=>$request->password], $request->remember));
if (!$authenticated) {
return redirect()->back()->withInput($request->only('email','remember'));
}
// We already have a auth user
$redirectRoute = $this->determineBackendRoute();
return redirect()->intended(route($redirectRoute));
}
/**
* Determine currently authenticated users destination backend
* */
public function determineBackendRoute () {
$role = auth()->user()->role_id;
switch ($role) {
case '1':
$route = 'vendor.dashboard';
break;
case '2':
$route = 'vendor.dashboard';
break;
default:
$route = 'home';
break;
}
return $route;
}
Overwrite the authenticated method in LoginController
protected function authenticated(Request $request, $user)
{
//write your logic's here
if ($user->role_id == 1) {
return redirect()->route('write the route name');
}
return redirect('/home');
}
Do something like this:
protected $redirectTo = '/user/home';
If based on usertype, do a condition statement that changes the value of $redirectTo

Categories