jeudi 30 mars 2023

Facebook data deletion request error when sending json response

When implementing the Facebook data deletion request, Facebook calls my method from their side and is telling me that the json response im sending back to them is not what they are expecting to receive. If you look at their documentation here Facebook Data Deletion Request. The response back to Facebook should be as follows

{ url: '<url>', confirmation_code: '<code>' }

The code Facebook posts in order to return this json is this

$data = array(
  'url' => $status_url,
  'confirmation_code' => $confirmation_code
);
echo json_encode($data);

Which does not create what Facebook is intending as a response. There literally needs to be no quotes around the name of the property and single quotes around the actual values. So I built that out using this

$return_value = "{ url: '$url', confirmation_code: '$confirmation_code' }";

Yes still no success. IM kind of at a loss here since I've been trying various methods with response()->json() json_encode() when returning either the $data array or $return string I create. That ends up putting double quotes around the entire string or put in escape characters around the url, which is think is one of the reasons why they are telling me the json is not what they are expecting. So if any one has a clue as to exactly how Facebook wants this response to look like. Please let me know. Thank you for your help

public function removeFBDataCallback(Request $request)
    {
        $signed_request = $request->get('signed_request');
        $data = $this->parse_signed_request($signed_request);
        $fb_user_id = $data['user_id'];

        $fb_user = $this->UsersRepository->CheckFacebookUIDExisted($fb_user_id);
  
        if (!$fb_user) {
  
            error_log("No user with facebook id: $fb_user_id found when trying to remove data during facebook deletion callback");
            return response()->json(['code' => 403, 'data' => ['message' => 'Facebook user not found when deleting facebook data']]);
        }
        else {
            

            $fb_delete_confirmation = new FBDeleteConfirmation();
            $fb_delete_confirmation->facebook_id = $fb_user->facebook_user_id;
            $fb_delete_confirmation->token = genToken(20);
            $fb_delete_confirmation->save();


            $fb_user->is_account_facebook = 0;
            $fb_user->facebook_user_id = null;
            $fb_user->save();

            
            $confirmation_code = base64_encode("abc123");
            $url = url('login').'/facebook'.'/dataDeleteConfirmation'.'?confirmationid'.('=').($confirmation_code);


            error_log('------------------');

            $return_value = "{ url: '$url', confirmation_code: '$confirmation_code' }";
            error_log($return_value);
            return json_encode($return_value);

        }
        
    } 


via Chebli Mohamed

How to add support for OPTION http verb to an apiResource?

I have APIs like this. I have a thousand of resources.

Route::apiResource('users', 'UserController')

The problem is I need to have also the OPTION verb enabled for all routes.

I could manually add option route to each route, but I am here asking if there is a way to do it automatically.

Actually the project is stalled on Laravel 5.6



via Chebli Mohamed

mercredi 29 mars 2023

Laravel: Product sorting based on categories

We are facing some issues while displaying the list of products with categories.

If there are 3 categories and each page contains 10 products on each page.

When we have 100 products, we need to show the listing with pagination. But the requirement is as below:

The list of products should be sorted like this: The first product from category 1 (In the list it will be in 1st place) The first product from category 2 (In the list it will be in 2nd place) The first product from category 3 (In the list it will be in 3rd place) The second product from category 1 (In the list it will be in 4th place) The second product from category 2 (In the list it will be in 5th place) The second product from category 3 (In the list it will be in 6th place) and So on...

We have product and category relation one to one relationship



via Chebli Mohamed

image upload from wamp(localhost) server to particular cpanel in laravel framework

I am trying to upload image from wamp server to direct upload in particular Cpanel in laravel framework. Is that possible .?

I want to upload image from any hosting site or localhost (wamp server) image will upload particular cpanel. Is that possible .?



via Chebli Mohamed

lundi 27 mars 2023

clicking on login button and return only to the index page in laravel

i have a problem and it isnt related with validation , im making my own login and register page and im not using start kits like breeze or jet stream ... when i click on the login button it must go and check the database if there is the same password and email then do something . but other to do anything it only return me to the same page like only i refresh the page , even if the email and password correct or not , it only refresh the page. why ?? This is the login form

<form class="login-form" action="" method="post">
    @csrf
    <img
        class="logo"
        src="https://www.logomaker.ckhfZt.png"
        alt="logo"
    />
    <label for="email">Email address:</label>
    <input
        type="text"
        id="email"
        name="email"
        placeholder="Enter email address"
        required
    />

    <label for="password">Password:</label>
    <input
        type="password"
        id="password"
        name="password"
        placeholder="Enter password"
        required
    />
    @error('failed')
    <div class="alert alert-danger" role="alert">
        
    </div>
    @enderror

    <input type="submit" value="Login" />
</form>

and this is the web file

Route::controller(AuthController::class)->group(function () {


    /* Register Route */

    Route::get('/register','register');
    Route::post('/store','store')->name('store');


    /* Login Route */

    Route::get('/','login');
    Route::post('/','loginCheck')->name('login-check');


    /* Home Route */
    Route::get('/home','home');

});

and this is the controller

class AuthController extends Controller
{
    public function login(){
        return view('auth.login');
    }
    public function register(){
        return view('auth.register');
    }

    public function home(){
        return view('home');
    }


    public function store(StoreRegisterRequest $request){

    $existingUser = DB::table('users')->where('email',$request->email)->first();
    if(!$existingUser){
        DB::table('users')->insert([
            'name' => $request->name,
            'email' => $request->email,
            'password'=> Hash::make($request->password),
        ]);
        return redirect('/');
         }
    }


    public function loginCheck(StoreRegisterRequest $request)
    {
        $user = DB::table('users')->where('email', $request->email)->first();
    
        if ($user && Hash::check($request->password, $user->password)) {
            // Credentials are valid, so start the session
          return $user;
        }
    
        // Invalid credentials, so return an error message
        return back()->withErrors(['failed' => 'Invalid login credentials.']);
    }
    
    

}

what is the problem why i cant see the user variable or i cant return to any other path?

im expecting my problem to be solved



via Chebli Mohamed

Call to undefined method App\Http\Controllers\UserController::successResponse() (500 Internal Server Error)

I am so confused by this error because this is my first time in back end subject , our instructor didn't included the CRUD operations on the video he provided so I decided to discover all by myself then I came up with this error on POST operation

HTTP - CONTROLLER - USER CONTROLLER PHP


<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
Class UserController extends Controller {
  private $request;
public function __construct(Request $request){
  $this->request = $request;
}
public function getUsers(){ 
  $users = User::all();
  return response()->json($users, 200);
}

public function add(Request $request ){
  $rules = [
  'first_name' => 'required|max:20',
  'last_name' => 'required|max:20',
  // 'gender' => 'required|in:Male,Female',
  ];
  $this->validate($request,$rules);
  $user = User::create($request->all());
  return $this->successResponse($user,
 Response::HTTP_CREATED);
  }
} 

MODEL - USER PHP

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
class User extends Model{
public $timestamps = false;
protected $table = 'students';
// column sa table
protected $fillable = [
'first_name', 'last_name'
];
}

ROUTES - WEB PHP


<?php

/** @var \Laravel\Lumen\Routing\Router $router */

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/

$router->get('/', function () use ($router) {
    return $router->app->version();
});

$router->get('/users',['uses' => 'UserController@getUsers']);


$router->post('/postUsers', 'UserController@add'); // create new user record

This is the all good I cant identify where the error occured or I have something miss to put

I just want to run the POST in postman to add data on column because I think POST is updating the database

so this is the data that I want to add

{ "first_name": "Lorem", "last_name": "Ipsum" }



via Chebli Mohamed

dimanche 26 mars 2023

How to use refresh token functionality in lcobucci/jwt using laravel 5?

Unable to implement refresh token code

currently im generating token using this vendor in-build functions. Already implemented the create token functionality, but every token has a expiry time once the token reaches its expiry time i needs to use refresh functionality to regenerate new token. dont know to to implement it.

Here's my existing code for create token,

Authcontroller.php
$token = $user->createToken($request->CLIENT_ID, 
                $scope_data_array
                )->accessToken;

HasApiTokens.php (Laravel/passport inbuilt function)
public function createToken($name, array $scopes = [])
    {
        log::debug("--inside createToken");
        return Container::getInstance()->make(PersonalAccessTokenFactory::class)->make(
            $this->getKey(), $name, $scopes
        );
    }


via Chebli Mohamed

samedi 25 mars 2023

Not counting duplicate data

I need a querybuilder query that calculates how many different people the user is messaging without counting the repetitive data.

database photo

Example:

conver_user_id = 165, conver_user_seller_id = 156
conver_user_id = 165, conver_user_seller_id = 156
conver_user_id = 165, conver_user_seller_id = 156
conver_user_id = 165, conver_user_seller_id = 158
conver_user_id = 165, conver_user_seller_id = 158

the result i want : Total count: 2

I will be glad if you help me thank you



via Chebli Mohamed

Laravel 5.5 query with groupBy('userid') works but when run from schedule

$allrecords = Records::all()->groupBy('userid');

this line in function works when run directly BUT: when run function with this line with schedule running stops in this line without raising any error. why? what to do?



via Chebli Mohamed

dimanche 12 mars 2023

White Blank Page in a Laravel Project Rather Than Showing Error

I'm so tired! Due to any kind of error in my laravel project running on localhost, I am getting blank white page! Running from XAMPP's htdocs, at least the routes that have no errors are coming up fine, although routes with error are showing blank white page. Running the project via "php artisan serve" command gives this type of error.

**

Warning: Unknown: failed to open stream: No such file or directory in Unknown on line 0 Fatal error: Unknown: Failed opening required 'C:\xampp\htdocs\pstu\server.php' (include_path='C:\xampp\php\PEAR') in Unknown on line 0

**

Please don't give me the solutions like here (https://stackoverflow.com/questions/27192237/laravel-5-env-local-debug-true-no-errors-shown). I have already tried everything of this link, Nothing worked for me.

Please don't give me the solutions like here text. I have already tried everything of this link, Nothing worked for me.



via Chebli Mohamed

vendredi 10 mars 2023

Uncaught ReferenceError: jQuery is not defined at dataTables.buttons.min.js:5:283

enter image description herei hosted two project in single domain. in root hosted react js and in subfolder hosted laravel. project working but cant access js css

i will try hosting two project in single domain with the help of subfolder



via Chebli Mohamed

jeudi 9 mars 2023

how to solve error in code i need upload formats to the image from jpg, jpeg

I need to upload all the formats to the image from jpg, jpeg, so I can upload one image format, which is png, can help me thank you

I need to upload all the formats to the image from jpg, jpeg, so I can upload one image format, which is png, can help me thank you



via Chebli Mohamed

Is there a way to override the .env.testing PHPUnit env variable for a specific test?

I am trying to override an ENV variable I set up in .env.testing, currently the implementation uses:

env('APP_ENV') which returns the value from .env.testing

However, I would like the value to be different for a specific test case. Solutions I have tried:

$_SERVER["APP_ENV"] = "local";

env('APP_ENV', 'another_value')

Any clues would be appreciated, I cannot find anything else online



via Chebli Mohamed

mercredi 8 mars 2023

Laravel auth::check return false but session exists

Many times a day Auth::check()return false.

The session is stored in redis and it exists and is not expired. Why Auth::check() should return false?

This happen many times a day for all users in the same time. ex: at 2PM all users has been logged out... at 4:38PM again, and so on.

We have laravel 5.8 and redis to store the sessions. Our app is running on a docker container



via Chebli Mohamed

mardi 7 mars 2023

Why is laravel serving me old versions of Model file

I have laravel 5.8 installed in DigitalOcean and I recently updated my code, I don't have cache enabled and yet each time I update the code, it doesn't use the new updates ... and in Sentry I receive bugs about the old code when it doesn't exist anymore, the line Sentry highlighted doesn't exist. I tried rebooting the server, restarting apache, deleting the file and uploading it again, changing the name of the function but nothing helped. Is there another cache I'm unaware of? knowing that it never happened to me



via Chebli Mohamed

lundi 6 mars 2023

Laravel: App::runningUnitTests() returns false while running unit tests

I am running unit tests on Laravel 5 and as the questions explains itself, App::runningUnitTests() is returning false during unit tests run. Why is that happening?

My PHP version is 7.1.



via Chebli Mohamed

dimanche 5 mars 2023

Laravel Call to a member function getFrameFilters() on null in

I was developing a funcionality on the dashboard of an app and unfortanetly the app sudently crashed. Supposetly the part I was developing isn't suppose to crash anything since it's on the frontend side of the app, it may be from the migration my collegue is doing but since i didn't did any git pull it's not suppose to crash. The app was originatly in Laravel 5 and where making the migration to Laravel 8.

This is the log:

[Sun Mar  5 12:49:53 2023] PHP Fatal error:  Uncaught Error: Call to a member function getFrameFilters() on null in /home/bernandre07/Desktop/dev/php/lanparty/website/vendor/filp/whoops/src/Whoops/Handler/PlainTextHandler.php:285
Stack trace:
#0 /home/bernandre07/Desktop/dev/php/lanparty/website/vendor/filp/whoops/src/Whoops/Handler/PlainTextHandler.php(189): Whoops\Handler\PlainTextHandler->getTraceOutput()
#1 /home/bernandre07/Desktop/dev/php/lanparty/website/vendor/filp/whoops/src/Whoops/Handler/PrettyPageHandler.php(292): Whoops\Handler\PlainTextHandler->generateResponse()
#2 /home/bernandre07/Desktop/dev/php/lanparty/website/vendor/filp/whoops/src/Whoops/Run.php(398): Whoops\Handler\PrettyPageHandler->handle()
#3 /home/bernandre07/Desktop/dev/php/lanparty/website/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(345): Whoops\Run->handleException()
#4 /home/bernandre07/Desktop/dev/php/lanparty/website/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(324): Illuminate\Foundation\Exceptions\Handler->rend in /home/bernandre07/Desktop/dev/php/lanparty/website/vendor/filp/whoops/src/Whoops/Handler/PlainTextHandler.php on line 285

I tried to search on google the error but I didn't found a thing.



via Chebli Mohamed

samedi 4 mars 2023

Why I'm I getting a 405 Method Not Allowed when submitting forms - Laravel

I'm working on a countdown website where I have 2 forms in the same view, every time I submit 1 of those forms I'm getting a error that says:

"message": "The POST method is not supported for route /. Supported methods: GET, HEAD."

The method that I'm using in the view is a GET method and the method that I'm using in the action route of the forms are POST method.

Now, I'll show you the routes and the HTML:

My routes:

routes

HTML Form 1:

html form 1

HTML Form 2:

html form 2

I've tried by setting the hidden method with Laravel using @method('POST') in the form, but it doesn't even works, I've also tried setting the same route to the routes on the web.php file like this:

Route::get('/', function () {
    return view('welcome');
});


Route::post('/', [App\Http\Controllers\EmailController::class, 'sendEmail'])->name('send.email');
Route::post('/', [App\Http\Controllers\EmailController::class, 'saveEmail'])->name('save.email');

, but doesn't works too, every time I tried it, I was getting this error:

error

and other things that I have tried by watching YouTube tutorials and StackOverflow posts, but how I said before nothing works

I would be very grateful if you could help me.



via Chebli Mohamed

jeudi 2 mars 2023

Validate email containing special characters in Laravel [duplicate]

I am trying to validate email id which shouldn't contain some special characters using regex. There are other answers on stack overflow and i have taken this regex looking at those answers but it doesn't work.

I have tried different format of regex but none of them doesn't look to be a perfect fit or does not work.

For example, users must not register containing following special characters. *, !, #, $, &, \, ", '.

Following is the regex i am using but getting an error. I tries with other formats as well.

'email' => [
    'required', 
    'email',
    'unique:users',
    "regex:/^([^\"!'#\$\*\\]*)$/"
]

For this getting an error: preg_match(): Compilation failed: missing terminating ] for character class at offset 16

Not good at regex so if any one can give some inputs to resolve the issue.



via Chebli Mohamed

mercredi 1 mars 2023

could we integrate google recaptcha v3 without any form or submit button with php

My home page have many forms and i want to implement google recaptcha v3 with all form but it will be irritating to implement google recaptcha v3 with all forms in single page individually.So i want to implement recaptcha with page not to all individual forms.

I did implemented recaptcha v3 individually with all html forms in a single page.I want to implement recaptcha without html form.



via Chebli Mohamed