dimanche 2 avril 2023

Attempt to read property "nom" on null

I am facing this error 'Attempt to read property "nom" on null' in Laravel 10. though the User eloquent model work fine beside for Plaques;

Here is my Code:

Plaques Model:

class Plaques extends Model
{
    use HasFactory;

    protected $table = 'Plaques';

    protected $fillable = ['nom', 'zone', 'el_plaque', 'tranche', 'gc_mecanise', 'gc_trad', 'gpon', 'ville', 'status_plaque', 'closed_by' , 'created_by'];

    public function chambres()
    {
        return $this->hasMany(Chambres::class);
    }

    public function immeuble()
    {
        return $this->hasMany(Immeuble::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Chambres Model:

class Chambres extends Model
{
    use HasFactory;

    protected $table = 'Chambres';

    protected $fillable = ['ref_chambre', 'type_chambre', 'chambre_terminer', 'loc_x_chambre', 'loc_y_chambre', 'plaque_id', 'user_id', 'status_chambre', 'created_by', 'closed_by', 'affected_by'];

    public function photos()
    {
        return $this->hasMany(Photos::class);
    }

    public function immeuble()
    {
        return $this->hasMany(Immeuble::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function plaques()
    {
        return $this->belongsTo(Plaques::class);
    }

}

ChambresController:

use App\Models\Chambres;
use App\Models\Plaques;
use App\Models\User;

class ChambresController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return view('admin.chambres.index')
        ->with('chambres', Chambres::get());
    }

View:

<tbody>
            @forelse ($chambres as $chambre)
            <tr>
                <th scope="col"><a href= "/admin/chambres/" class="badge badge-primary" role="button"> </a></th>
                <th scope="col"></th>
                <th scope="col"></th>
                <th scope="col"></th>
                <th scope="col"><a href= "/admin/chambres//edit" class="badge badge-primary" role="button"> Modifier </a></th>
                <th scope="col">
                    <form id="valider" action="/admin/chambres/" method="post" class="hidden">
                    @csrf
                    @method('delete')
                    <button class="btn" role="button">Supprimer</button>
                </form>
                </th>
            </tr>

Chambres Migration:

        Schema::create('chambres', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id')->nullable();
            $table->unsignedBigInteger('plaque_id')->nullable();
            $table->string('ref_chambre')->unique();
            $table->string('type_chambre');
            $table->date('chambre_terminer')->nullable()->change();
            $table->string('loc_x_chambre');
            $table->string('loc_y_chambre');
            $table->boolean('status_chambre')->nullable();
            $table->string('created_by')->nullable();
            $table->string('closed_by')->nullable();
            $table->string('affected_by')->nullable();
            $table->foreign('plaque_id')->references('id')->on('plaques')->onDelete('cascade');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
        });

i want to get 'nom' column value from 'Plaques' table which has foreign key on 'Chambres' table.



via Chebli Mohamed

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

mercredi 29 mars 2023

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

Laravel Excel migration from V2.1 to V3.1

I'm working on one project where I have used V2.1 and now I'm planning to upgrade package from V2.1 to V3.1

The old code looks something like following:

function getReportOfXYZ(DocumentAnalysis $documentAnalysis) {
  // get data from DB and store it in records array
  $companyName = $records['CompanyName'];
 
  
  $file = Excel::load(public_path('Template.xls'));

  $sheet = $file->setActiveSheetIndexByName('Data XYZ');

  $sheet->setCellValue('B2', $companyName);
  $sheet->setCellValue('B6', 'Year 1');
  $sheet->setCellValue('C6', 'Year 2');`your text`

  $year = 1;

  while ($year <= 2) {
    foreach ($records as $key => $value) {
      switch (strtolower($key)) {
        // BALANCE SHEET
        case 'balance_sheet':
        if ($value) {
          foreach ($value as $dataKey => $data) {
            switch (strtolower($dataKey)) {

              case 'cash and cash equivalents':
              $entity = array_sum([
                $data['Year '.$year.'A'],
                $data['Year '.$year.'B'],
                $data['Year '.$year.'C'],
                $data['Year '.$year.'D']
              ]);
              $sheet->setCellValueByColumnAndRow($year, 10, (string)$entity);
              break;
            }
          }
        }
      }
    }
  }

  $file->export('xls');
}

I'm not sure how to load file and update it on the fly in v3.1

I reviwed their migration guide https://docs.laravel-excel.com/3.1/getting-started/upgrade.html but not able to find a way to fix my issue.



via Chebli Mohamed

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