mardi 30 mai 2023

how to view the speed of the request to the backend in php?

i have a laravel application and i want to echo out the current speed it takes the server to load the page or whatever. as I'm using Redis i want to make sure that way it actually caching it and the page will load faster the next time(if the user is moved to google or whatever and come back or if the user moved to other page in my site and come back to lets say the home page).

I want to know how can i implement it in my application.

as i added Redis but i do not see anything faster.

i did this in Redis config file:

sudo apt install redis-server

sudo nano /etc/redis/redis.conf

changed supervised no to supervised systemd.

and make sure it run ok by running redis-cli and running inside the prompt: ping which gave me PONG response.

then, in my .env file i changed this: CACHE_DRIVER=file to this: CACHE_DRIVER=redis. and restarted nginx to make sure it got the changes. and no errors at all.



via Chebli Mohamed

Cannot use object of type GuzzleHttp\Psr7\Response as array in file

I am new in laravel, I am getting an error when I am trying to access elements of json response in this case being access_token

details of the error:

'Cannot use object of type GuzzleHttp\Psr7\Response as array in file /home/chefane/myProjects/paylesotho/app/Http/Controllers/Api/EletricityController.php on line 34'

below I created a function that returns data in json format, now the trick is how to access one of the elements. below is what I did:

 public function getToken(Request $request){

        $url = Config('api.url');

        $client = new \GuzzleHttp\Client();
        $headers = [
        'Content-Type' => 'application/x-www-form-urlencoded',
        ];
        
        $response = $client->request('POST', $url, [$headers,
        'form_params' => [
            'client_id' => Config('api.client_id'),
            'client_secret' => Config('api.client_secret'),
            'username' => Config('api.username'),
            'password' => Config('api.password'),
            'grant_type' => 'password',
            'scope' => 'read write openid'
            ]  
        ]);
      
        $data = json_decode($response->getBody(),true);
        $key_value =   $response['access_token'];
        return $key_value;
    }

below is what the function returns:

{
 "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJlUktVWG10TFhKMHBBNkxBS29aWko1ZlU0VDhCdmxKdERCb3pXanFFdnhjIn0.eyJleHAiOjE2ODU0ODUzOTMsImlhdCI6MTY4NTQ0OTM5MywianRpIjoiYWYxNTI5ZjAtNTdmYS00MjgyLWIzYTEtZWNlMzZlNjY4MzU2IiwiaXNzIjoiaHR0cHM6Ly9leHRhdXRoLmZpbmNsdWRlLmNvLnphL2F1dGgvcmVhbG1zL2ZpbmNsdWRlIiwic3ViIjoiZDNhNTNiZTgtZDgyOS00ZmU4LWI4ZmUtNGQzNDVkNzAzNWY4IiwidHlwIjoiQmVhcmVyIiwiYXpwIjoiQjJCX0FQSSIsInNlc3Npb25fc3RhdGUiOiJlNjE3MjdjNi03ZjdhLTQ4NDItODg0ZC1lNTdhY2UyYjczMDEiLCJhY3IiOiIxIiwic2NvcGUiOiJvcGVuaWQgcHJvZmlsZSByZWFkIHdyaXRlIiwicHJlZmVycmVkX3VzZXJuYW1lIjoicGF5bHNhcGkifQ.GSsBQxBA7ge0iXnLK3xvlkAXGPgT7DjfOGzB6JsNMJfjB9iqtE2tMHdKwOtIKOnCkZMeDQI1BJxoc-5voGNUeDVwNzJkP9DBnE3EbUZRs6_u4-flQdA2Ir0s3pZm3Cmn6q_iHWpBGEzPlQohbV26G3wEO6Y8qJ5oXz8A_t-IsoIWJzyVQvtTpu8Uqde43_XB9okzS0wtMaYLCUlNXl263eTkmP0fzOoXGfjUhuil_2ALxErCFSiBqCCfhsc8U5Om1Zpcz2cgrUkq_7ZEUF2VV4c7fZIjRsugx7n9zfQ-PqkQ7YznjI5mmbn-mnE7o0PGqw_p_goTvpf2pGZI5mdayg",
    "expires_in": 36000,
    "refresh_expires_in": 1800,
    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICIwZDkwY2JkNy03MTY0LTQyY2MtODhlMi1kMjE1ZTc5YWU4ZWEifQ.eyJleHAiOjE2ODU0NTExOTMsImlhdCI6MTY4NTQ0OTM5MywianRpIjoiZTA0NzY3YjctZmUyMS00MTdlLWE2ZGQtZDdhNGQ0ZGMxODIwIiwiaXNzIjoiaHR0cHM6Ly9leHRhdXRoLmZpbmNsdWRlLmNvLnphL2F1dGgvcmVhbG1zL2ZpbmNsdWRlIiwiYXVkIjoiaHR0cHM6Ly9leHRhdXRoLmZpbmNsdWRlLmNvLnphL2F1dGgvcmVhbG1zL2ZpbmNsdWRlIiwic3ViIjoiZDNhNTNiZTgtZDgyOS00ZmU4LWI4ZmUtNGQzNDVkNzAzNWY4IiwidHlwIjoiUmVmcmVzaCIsImF6cCI6IkIyQl9BUEkiLCJzZXNzaW9uX3N0YXRlIjoiZTYxNzI3YzYtN2Y3YS00ODQyLTg4NGQtZTU3YWNlMmI3MzAxIiwic2NvcGUiOiJvcGVuaWQgcHJvZmlsZSByZWFkIHdyaXRlIn0.t-ye9K9pBtMGQidk6SvYCP7Aa_uDV9_9wGXyeFbbbz0",
    "token_type": "bearer",
}

I want the function to return only the access_token



via Chebli Mohamed

samedi 27 mai 2023

How can I customize my own route for login and register in Jetstream but keep the same post method?

I'm using jetstream in my project and I have a problem, by default in jetstream there are many routes like login and register...

I have made a /auth route in web file,this route return a page that contains register and login form, it means that the 2 forms are inside the same route. Now my problem is I want to disable the default/login and /register get routes or I want to change them to /auth, so I want to custom my own route for the login and register route but there is an important thing that I want to use the same post method for Both login and register routes I don't want to make all authentication code like authentication and session from zero 🤦 my code code for register and login post method will not be secure like the default, so how can I do that

I tried to do something like return 404 page when user visit register and login route in web.php file but maybe it's not the true idea🤦



via Chebli Mohamed

Troubleshooting Laravel 5.4 Messaging App: 'Open' button not functioning as expected on the received page

messages controller or received page does not work as the open button does not open the conversation that is in the received page.

I'm trying to make it work but I do not know why it does not work. I really do not have an explanation for why it does not work. what should I fix and where?

btw. there is probably an error(i think it is there as the open button does not work for some reason) in the received.blade.php file

this is the files of the messages:

app/Message.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Message extends Model
{
    public function To(){
      return $this->belongsTo('App\User','to');
    }
    public function From(){
      return $this->belongsTo('App\User','from');
    }
}

app/Http/Controllers/MessageController:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;
use App\User;
use App\Message;

class MessageController extends Controller
{
    public function SendView($username = null){
      $user = Auth::user();
      $recipient = User::where('username',$username)->first();
      return view('message.send')->with([
        'recipient' => $recipient
      ]);
    }

    public function SendPost(Request $request){
      if ($request->recipient == null) {
         session()->flash('errormessage','You must enter recipient\'s username');
         return redirect()->back()->withInput();
      }
      if ($request->text == null) {
         session()->flash('errormessage','You must send something');
         return redirect()->back()->withInput();
      }
      if ($request->title == null) {
         session()->flash('errormessage','You must enter title');
         return redirect()->back()->withInput();
      }
      $recipient = User::where('username',$request->recipient)->first();
      if ($recipient == null) {
        session()->flash('errormessage','User with that username does not exist');
        return redirect()->back()->withInput();
      }
      if ($recipient->id == Auth::user()->id) {
        session()->flash('errormessage','You cannot send message to yourself');
        return redirect()->back()->withInput();
      }
      $last_msg = Message::where('from',Auth::user()->id)->orderBy('created_at','desc')->first();
      if ($last_msg !== null) {
        $newTime = date("Y-m-d H:i:s",time());
        if (Auth::user()->vendor == false) {
          $last_time = date('Y-m-d H:i:s',strtotime('+1 minute',strtotime($last_msg->created_at)));
          if ($newTime < $last_time) {
            session()->flash('errormessage','You can send message every minute');
            return redirect()->back()->withInput();
          }
        } else {
          $last_time = date('Y-m-d H:i:s',strtotime('+10 seconds',strtotime($last_msg->created_at)));
          if ($newTime < $last_time) {
            session()->flash('errormessage','You can send message every ten seconds');
            return redirect()->back()->withInput();
          }
        }
      }

      $m = new Message;
      $m->uniqueid = 'ME'.str_random(28);
      $m->to = $recipient->id;
      $m->from = Auth::user()->id;
      $m->title = $request->title;
      $m->text = $request->text;
      $m->save();
      return redirect()->route('messages');
    }

    public function ViewReceived(){
      $received = Message::where('to',Auth::user()->id)->orderBy('created_at','desc')->paginate(25);
      return view('message.received')->with([
        'received'=>$received
      ]);
    }

    public function ViewSent(){
      $sent = Message::where('from',Auth::user()->id)->orderBy('created_at','desc')->paginate(25);
      return view('message.sent')->with([
        'sent'=>$sent
      ]);
    }
    public function ViewMessage($uniqueid){
      $message = Message::where('uniqueid',$uniqueid)->first();
      if ($message == null) {
        return redirect()->route('messages');
      }
      if (Auth::user()->id !== $message->to && Auth::user()->id !== $message->from) {
          return redirect()->route('messages');
      }
      if ($message->viewed == false && Auth::user()->id == $message->to) {
         $message->viewed = true;
         $message->save();
        }
        return view('message.view')->with([
           'message'=>$message
        ]);
    }
}

routes/web.php:

Route::get('message/send/{username?}','MessageController@SendView')->name('sendmessage');
  Route::post('message/send','MessageController@SendPost')->name('sendmessagepost');

  Route::get('messages/received','MessageController@ViewReceived')->name('messages');
  Route::get('messages/sent','MessageController@ViewSent')->name('messagessent');

  Route::get('message/view/{uniqueid}','MessageController@ViewMessage')->name('viewmessage');

resources/views/message/received.blade.php:

@extends('master.main')

@section('main-content')

  @component('master.notification')
    @slot('size')
    col-md-8 col-md-offset-2
    @endslot
    @slot('title')
    My messages
    @endslot
    <div class="row">
      <center>
        <a href="" class="btn btn-primary">Send new message</a>
      </center>
    </div>
    <div class="row">
      <ul class="nav nav-tabs">
      <li role="presentation" class="active"><a href="">Received</a></li>
      <li role="presentation"><a href="">Sent</a></li>
      </ul>
    </div>
    <table  class="table table-hover">
      <thead>
        <th>From</th>
        <th>Title</th>
        <th>Time</th>
        <th>Action</th>
      </thead>
      <tbody>
        @foreach($received as $r)
          <tr>
            <td> @if($r->viewed == false)<span class="label label-default">didnt read it yet</span> @endif</td>
            <td></td>
            <td></td>
            <td><a href="" class="btn btn-default">Open</a></td>
          </tr>
        @endforeach
      </tbody>
    </table>
    <div class="form-group">
      <center>
        
      </center>
    </div>

  @endcomponent

@stop

resources/views/message/view.blade.php:

@extends('master.main')

@section('main-content')

  @component('master.notification')
    @slot('size')
    col-md-8 col-md-offset-2
    @endslot
    @slot('title')
    Message from <span class="font-weight-600"></span> sent to <span class="font-weight-600"></span>
    @endslot

      <div class="from-group">

      </div>
      <div class="form-group">
        <label for="title">Title:</label>
        <input type="text" name="title" id="title" value="" class="form-control" readonly="">
      </div>
      <div class="form-group">
        <label for="text">Text:</label>
        <textarea name="text" class="form-control" style="resize:none" rows="8" cols="80" readonly=""></textarea>
      </div>
      <div class="form-group">
        <center>
        @if(Auth::user()->id == $message->To->id)
        <a href="" class="btn btn-primary">Reply</a>
        @elseif(Auth::user()->id == $message->From->id)
          <a href="" class="btn btn-primary">Send another message to </a>
        @endif
        </center>
      </div>


  @endcomponent

@stop

I'm using laravel 5.4 and everything else in project is working perfectly fine. only this open button in the received page does not work.



via Chebli Mohamed

jeudi 25 mai 2023

how to work submenu when not getting submenu2

`When not Getting Submenu2 My subMenu route not working in this menu and when getting submenu2 only working submenu2 route..

ii will try when not getting submenu2 then submenue route working but when click submenu i saw console route showing but not clickin any one please kindly help for me ....`

@foreach ($menu as $item=>$value)

@foreach($data as $ddata)

@if($value->user_group_id==$ddata->user_group_id)
<li class="nav-item d-sm-inline-block has-treeview menu-close" style="font-size:14px; color:white;">
    <a href="#" class="nav-link">
        <i class="nav-icon fas fa-tachometer-alt fa-lg"></i>
        <p> <i class="right fas fa-angle-left"></i></p>
    </a>

    <ul class="nav nav-treeview">
        @foreach($submenu as $submenus)

        @if($value->menu_item_id==$submenus->menu_item_id)
        <li class="nav-item has-treeview menu-close">
            <a href="" class="nav-link active">
                <i class="far fa-circle nav-icon"></i>
                <i class="right fas fa-angle-left"></i>
            </a>
            @if($submenu2->count()>0)
            <ul class="nav nav-treeview">
                @foreach($submenu2 as $submenus2)

                @if($submenus->sub_menu_id==$submenus2->sub_menu_2)
                <li class="nav-item has-treeview menu-close">
                    <a href="" class="nav-link active">
                        <i class="far fa-circle nav-icon"></i>
                        <i class="right fas fa-angle-left"></i>
                    </a>

                </li>
                @endif
                @endforeach
            </ul>
            @endif
        </li>
        @endif
        @endforeach
    </ul>
</li>
@endif

@endforeach

@endforeach

ii will try when not getting submenu2 then submenue route working but when click submenu i saw console route showing but not clicking ...



via Chebli Mohamed

Unable to Resolve Vue Components in Laravel 9 with Vue.js, Inertia, and Custom Admin Directory

I'm using Laravel 9 with vue.js and Inertia. The thing is there is a small issue that I'm facing. In my "resources/js/Pages" directory I have all the vue files. Now what I want to do is create an additional directory for admin users in the "resources/js/Pages/Admin" directory and store all the vue files related to admin users there.

Following is the code of my app.js file:

import { createApp, h } from 'vue'
import { createInertiaApp } from '@inertiajs/inertia-vue3'
import './bootstrap';
import '../css/app.css'; 

createInertiaApp({
  resolve: name =>
   import(`./Pages/${name}.vue`),
  setup({ el, App, props, plugin }) {
    createApp({ render: () => h(App, props) })
      .use(plugin)
      .mount(el)
  },
})

Now I have created the directory in "resources/js/Pages" and named it "Admin". And inside that directory I have created a vue file "Admin_login.vue"the and following is the basic content of it:

<template>
    <h1>Admin Page</h1>
</template>

Now I want to access that file for that I have created the following route into my web.php file

Route::get('/Admin_Login', function () {
    return Inertia::render('Admin/Admin_login');
});

But I can not access the desired page and I don't know where I'm making the mistake.

I have modified the app.js file into the following code, but unfortunately it was not working as well

import { createApp, h } from 'vue'
import { createInertiaApp } from '@inertiajs/inertia-vue3'
import './bootstrap';
import '../css/app.css'; 

createInertiaApp({
  resolve: (name) => {
    if (name.startsWith('Admin_')) {
      const adminName = name.replace(/^Admin_/, 'Admin/');
      return import(`./Pages/${adminName}.vue`);
    }

    return import(`./Pages/${name}.vue`);
  },
  setup({ el, App, props, plugin }) {
    createApp({ render: () => h(App, props) })
      .use(plugin)
      .mount(el)
  },
});


via Chebli Mohamed

mardi 23 mai 2023

Laravel date changes to 1st January 1970 when passed from blade template to model in a function call

I have a larav`el project where I produce balance sheet by getting ledger opening balance and aggregating transactions that occurs between two dates say 01/01/2023 to 31-03-2023.

The controller fetches all ledger transactions between start_date and end_date as requested by the user. It forward the records and the two dates to a blade file.

Shown below is the code segment within the blade file where a call a method in a model

***<?php dd($start_date, $end_date); ?>***
<td></t`d>
<td>
<?php  $currYrResult = **$ppe->getBalance($start_date, $end_date, null, true)** ?>
<?php  $currPpeTotal = bcsub($currYrResult['balance'], $curr_accum_depreciation['ppeTotal'], 2) ?>
........
</td> 

From within the blade code shown above, I call a Model method using $ppe->getBalance($start_date, "yes", null, true) passing the two dates but in the model method the end_date is 1970-01-01 instead of 2023-03-31 passed from the blade

the above statement in the blade file prints 2023-01-01 and 2023-03-31

but in the method getBalance, when I prints the date as shown in the code segment below, I get 2023-01-01 and 1970-01-01

public function getBalance($start_date = null, $end_date = null, $year = null, $accumulate = null)    {
*dd($start_date, $end_date);*
$dr_total = $this->getDebitBalance($start_date, $end_date, $year, $accumulate);
$cr_total = $this->getCreditBalance($start_date, $end_date, $year, $accumulate);

Please your assistance will be appreciated

I tried using createDateFromFormat to no avail. When I pass end_date as value instead of variable I get same issue



via Chebli Mohamed

Get data from adyen

How do we get liability shift, fraud score from adyen api which is integrate into laravel 5.4 as SDK?

    try {
        $adyen = new AdyenClient();
        $params = array(
            'merchantAccount' => 'MozillionLimitedMP',
            'originalReference' => $order->transcation_id // Replace with the actual PSP reference
        );

        $paymentResult = $adyen->service->getPaymentResult($params);
        $liabilityShift = $paymentResult['paymentResult']['liabilityShift'];
        $fraudScore = $paymentResult['paymentResult']['fraudResult']['score'];

        // Process the liability shift and fraud score accordingly
    } catch (\Exception $e) {
        dd($e);
        // Handle the error
        $bankAccountStatus = ['error' => $e->getMessage()];
    }


via Chebli Mohamed

dimanche 21 mai 2023

problem laraver php artisan migrate:fresh --seed

I have a problem about my project backend laravel I can't connact server (page admin) I use coomaned but all try fill

php artisan config:cache php artisan cache:clear
php artisan migrate php artisan serve

composer install composer update php artisan serve --host=0.0.0.0 php artisan migrate:fresh --seed

php artisan migrate:fresh --seed

I want to cry

--


php artisan config:cache php artisan cache:clear
php artisan migrate php artisan serve Cmd

composer install php artisan serve --host=0.0.0.0 php artisan migrate:fresh --seed

php artisan migrate:fresh --seed php artisan migrate:fresh --seed php artisan serve --host=0.0.0.0 php artisan serve --host=0.0.0.0 php artisan migrate:fresh --seed



via Chebli Mohamed

vendredi 19 mai 2023

what are the ways that i can use in laravel 10 to change the engine in my sql by creating a new migration?

i want to change the mysql innoDB engine to MyISAM using laravel migration i created the migration that is names alter_products_engine that is suppose to change the table products but that is not happining

i made the table migration like below and i am expected the change happens but it dose not

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('products');
    }
};

and also the alter table migration

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('products',function(Blueprint $table){
            $table->engine = 'MyISAM';
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('products',function(Blueprint $table){
            $table->engine = 'MyISAM';
        });
    }
};


via Chebli Mohamed

jeudi 18 mai 2023

Background image in Maatwebsite excel laravel

I am using laravel 9 and using Maatwebsite. I want to set background image in excel. Here I did

class myExport implements FromView, WithEvents ,WithDrawings
{

  public function view(): View
   {
     return view('report');
   }

   public function drawings()
    {
    $drawing = new Drawing();
    $drawing->setName('Background Text');
    $drawing->setDescription('This text ');
    $drawing->setPath(public_path('assets/img/draft.png'));
    $drawing->setCoordinates('A1'); 

    return [$drawing];
}

Image shows successfully but not appears in background . Thanks inadvance

Also tried with

public function registerEvents(): array
{

    return [
        BeforeSheet::class => function (BeforeSheet $event) {
            $spreadsheet = new Spreadsheet();
            $event->sheet->getDelegate()->setActiveSheetIndex(0);
            $event->sheet->getDelegate()->getActiveSheet()
                ->getHeaderFooter()
                ->setOddFooter('&L&BPage &P of &N');

            $event->sheet->getDelegate()->getActiveSheet()
                ->setShowGridlines(false); // Optional: Hide gridlines

            $event->sheet->getDelegate()->getActiveSheet()
                ->setSheetBackground('assets/img/draft.png'); 
        },
    ]; 


via Chebli Mohamed

mercredi 17 mai 2023

Maatwebsite excel set watermark in laravel

I am using laravel 9 and using Maatwebsite. I want to make watermark in excel. Here I did

class myExport implements FromView, WithEvents ,WithDrawings
{

  public function view(): View
   {
     return view('report');
   }

   public function drawings()
    {
    $drawing = new Drawing();
    $drawing->setName('Background Text');
    $drawing->setDescription('This text ');
    $drawing->setPath(public_path('assets/img/draft.png'));
    $drawing->setCoordinates('A1'); 

    return [$drawing];
}

But this image not appears in background. Also it will be ok if I set any text

Thanks in advance.............



via Chebli Mohamed

vendredi 12 mai 2023

Error in TokenMismatchException and have CSRF token [closed]

I have a project in Laravel, everything worked fine, from one day to the next it stopped working correctly, I get an error in the token even though I am sending the token in the form, I clean the cache, the session, the configuration and it still does not take hold.

`(1/1) TokenMismatchException
in VerifyCsrfToken.php line 68
at VerifyCsrfToken->handle(object(Request), object(Closure))
in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in ShareErrorsFromSession.php line 49`

I tried with php artisan cache:clear, php crafty config:clear, clear the cache manually and could not solve



via Chebli Mohamed

jeudi 11 mai 2023

Attempt to read property "nom" on bool

Attempt to read property "nom" on bool

I use the show function which sends a data ($cultur) to ressource.blade.php which contains 2 add and edit forms I use 2 $cultur in add and edit so and displays errror



via Chebli Mohamed

mercredi 10 mai 2023

Laravel Homstead project can't be reach on Chrome

My Laravel project is working fine on firefox, but when i try it on Chrome i got "This site can’t be reached" and "Your connection with this site is not secure"

I'm using Homestead vagrant box and in .env file APP_URL: http://laravel-project.test

to be clear, project works in firefox, but is not reachable in chrome. I tried to import the ca.homestead.homestead.pem file from vagrant (/etc/ssl/certs) to Chrome > Privacy and security > Security > Manage certificates / Manage HTTPS/SSL certificates (tab Authorities) > import... and nothing has changed.

Does anyone have a similar problem or does anyone have an idea how to fix it as i need Chrome for debugging too?

Thanks in advance for any help and advice.



via Chebli Mohamed

mardi 9 mai 2023

File::makeDirectory() not creating directory [duplicate]

In my Laravel application, I'm trying to make a directory. I use the following code

$localPath = 'something'; 
File::makeDirectory($localPath);

It creates a directory when I run my application on local server (xampp). But when I host on my application on live server, it does not create the folder locally, instead, it creates the folder on the server under the 'public' folder.

Any help ??



via Chebli Mohamed

dimanche 7 mai 2023

Query builder all data loading

I want to show only the people the user is messaging, but all users are showing. How can i fix this?

SQL PHOTO: https://i.stack.imgur.com/6pOPa.png

 public static function otherUserData($user_id)

  {

    $value = DB::table('users')

    ->select(['*', DB::raw('MAX(conver_date) AS lastConver')])

    ->leftJoin('conversation', function ($join) use ($user_id) {

        $join->on('conversation.conver_seller_id', '=', 'users.id')

            ->on('conversation.conver_user_id', '=', DB::raw($user_id))

            ->orOn('conversation.conver_seller_id', '=', DB::raw($user_id))

            ->on('conversation.conver_user_id', '=', 'users.id'); 

    })

    ->where('user_type', '!=', 'admin')

    ->where('id', '!=', $user_id)

    ->where('drop_status', '=', 'no')

    ->orderBy('lastConver', 'desc')

    ->groupBy('id')

    ->get(); 



return $value;

  }

I would be very grateful if you could help.



via Chebli Mohamed

samedi 6 mai 2023

Query Builder Spefic Query

i want to show only the contacts that the user is messaging, I don't want the people that the user has not messaged to appear. How can i fix this?

DATABASE: DATABASE PHOTO

Query Command:

 public static function otherUserData($user_id)

  {

    $value = DB::table('users')

    ->select(['*', DB::raw('MAX(conver_date) AS lastConver')])

    ->leftJoin('conversation', function ($join) use ($user_id) {

        $join->on('conversation.conver_seller_id', '=', 'users.id')

            ->on('conversation.conver_user_id', '=', DB::raw($user_id))

            ->orOn('conversation.conver_seller_id', '=', DB::raw($user_id))

            ->on('conversation.conver_user_id', '=', 'users.id'); 

    })

    ->where('user_type', '!=', 'admin')

    ->where('id', '!=', $user_id)

    ->where('drop_status', '=', 'no')

    ->orderBy('lastConver', 'desc')

    ->groupBy('id')

    ->get(); 



return $value;

  }

I will be glad if you help me thank you.



via Chebli Mohamed

vendredi 5 mai 2023

when my laravel proj keep in wampp C:\wamp64\www than why this is use xampp version and ^7.1.3 your php version (8.1.6) not satisfy with requirement

enter image description here

Problem 29 - phpunit/php-file-iterator is locked to version 2.0.2 and an update of this package was not requested. - phpunit/php-file-iterator 2.0.2 requires php ^7.1 -> your php version (8.1.6) does not satisfy that requirement. Problem 30 - phpunit/php-timer is locked to version 2.0.0 and an update of this package was not requested. - phpunit/php-timer 2.0.0 requires php ^7.1 -> your php version (8.1.6) does not satisfy that requirement. Problem 31 - phpunit/php-token-stream is locked to version 3.0.0 and an update of this package was not requested. - phpunit/php-token-stream 3.0.0 requires php ^7.1 -> your php version (8.1.6) does not satisfy that requirement. Problem 32 - phpunit/phpunit is locked to version 7.3.5 and an update of this package was not requested. - phpunit/phpunit 7.3.5 requires php ^7.1 -> your php version (8.1.6) does not satisfy that requirement. Problem 33 - sebastian/code-unit-reverse-lookup is locked to version 1.0.1 and an update of this package was not requested. - sebastian/code-unit-reverse-lookup 1.0.1 requires php ^5.6 || ^7.0 -> your php version (8.1.6) does not satisfy that requirement. Problem 34 - sebastian/comparator is locked to version 3.0.2 and an update of this package was not requested. - sebastian/comparator 3.0.2 requires php ^7.1 -> your php version (8.1.6) does not satisfy that requirement. Problem 35 - sebastian/diff is locked to version 3.0.1 and an update of this package was not requested. - sebastian/diff 3.0.1 requires php ^7.1 -> your php version (8.1.6) does not satisfy that requirement. Problem 36 - sebastian/environment is locked to version 3.1.0 and an update of this package was not requested. - sebastian/environment 3.1.0 requires php ^7.0 -> your php version (8.1.6) does not satisfy that requirement. Problem 37 - sebastian/exporter is locked to version 3.1.0 and an update of this package was not requested. - sebastian/exporter 3.1.0 requires php ^7.0 -> your php version (8.1.6) does not satisfy that requirement. Problem 38 - sebastian/global-state is locked to version 2.0.0 and an update of this package was not requested. - sebastian/global-state 2.0.0 requires php ^7.0 -> your php version (8.1.6) does not satisfy that requirement. Problem 39 - sebastian/object-enumerator is locked to version 3.0.3 and an update of this package was not requested. - sebastian/object-enumerator 3.0.3 requires php ^7.0 -> your php version (8.1.6) does not satisfy that requirement. Problem 40 - sebastian/object-reflector is locked to version 1.1.1 and an update of this package was not requested. - sebastian/object-reflector 1.1.1 requires php ^7.0 -> your php version (8.1.6) does not satisfy that requirement. Problem 41 - sebastian/recursion-context is locked to version 3.0.0 and an update of this package was not requested. - sebastian/recursion-context 3.0.0 requires php ^7.0 -> your php version (8.1.6) does not satisfy that requirement.fy that requirement. Problem 42 - theseer/tokenizer is locked to version 1.1.0 and an update of this package was not requested. quirement. - theseer/tokenizer 1.1.0 requires php ^7.0 -> your php version (8.1.6) does not satisfy that requirement. Problem 43 y that requirement. - webmozart/assert is locked to version 1.3.0 and an update of this package was not requested. - webmozart/assert 1.3.0 requires php ^5.3.3 || ^7.0 -> your php version (8.1.6) does not satisfy that requirement.y that requirement. ny/http-foundation[v4.1.4]. Problem 44 sted. - symfony/http-foundation v4.1.4 requires php ^7.1.3 -> your php version (8.1.6) does not satisfy that requirement. - barryvdh/laravel-cors v0.11.2 requires symfony/http-foundation ^3.1|^4 -> satisfiable by symfony/http-foundation[v4.1.4]. - barryvdh/laravel-cors is locked to version v0.11.2 and an update of this package was not requested.



via Chebli Mohamed

jeudi 4 mai 2023

Redirection issue in laravel 5.6

I have one project in laravel 5.6 which is specifically with nginx and the issue that I am facing with that is if I hit the url with the HTTPS than the URL works fine but if the same URL, I hit with HTTP than it shows me the error.

Example:

Https://example.com

..this works fine and it redirect me to login page

Http:/example.com

..But in this case it shows me the error like not secure connection.

Although I have entered the proper code and redirect in web.php file and as well as in appserviceprovider.php to force fully redirect to HTTPS if the entered url is HTTP.

Anyone have any idea. How can I debug or how can I add any logging or any thing to find the exact issue? Please help me with this I really need to resolve this as it's blocker for me now.

I have entered the diffrent configuration code in nginx l.config file but didn't get any success.

Thanks.



via Chebli Mohamed

Laravel file storage issues

I have an issue with Laravel

Case:

  1. Create a file test.csv with data "abcdefg"
  2. Delete the file test.csv
  3. Recreate the file test.csv with data "zmamamama"

My code

$data = "asdsdsds";

 if(file_exists(storage_path('app/public/test/test.csv'))){
   unlink(storage_path('app/public/test/test.csv' ));
 }

Excel::store(new SomeTest($data), '/public/test/test.csv');

The issue is that test.csv still shows the old data ("abcdefg") even though the file o nthe local server show the new data accessed the file from the URL test.com/storage/test/test.csv

I'm using CentOS on the machine running my Laravel server.



via Chebli Mohamed

mercredi 3 mai 2023

Laravel MySQL Full text search InnoDB Relevancy Calculation for multiple rows with same number of occurences in total

using mysql from xaamp v8.1.10 along with laravel v5.5.3.

Full text Search Index enabled in table 'ex1' for column 'des' and 'ft_min_word_len = 1'.

laravel query:

$string='pink item product';

$result = ex::active()->selectRaw("*,match(des) against('$string' in boolean mode)  as relevance")->whereRaw("match(des) against('$string' in boolean mode)")->orderBy('relevance', 'desc')->get();

I am getting the result as

( results are truncated )

id Relevance des
64 1.3543391227722 amazing pink petite lace item is item.
182 1.3543391227722 this pink tall polyester item is item.
598 1.3543391227722 which pink large polyester item is item.
653 1.3543391227722 amazing pink plus size linen item is item.
808 1.3543391227722 what pink tall cashmere item is item.
19 1.344024181366 different pink large silk product is item.
134 1.344024181366 that pink large wool product is item.
140 1.344024181366 this pink tall lace item is product.
233 1.344024181366 new pink extra-small lace item is product.
273 1.344024181366 this pink tall cashmere item is product.
625 1.344024181366 amazing pink medium lace product is item.
893 1.344024181366 pink extra-small leather item is product.
908 1.344024181366 which pink tall lace product is item.
992 1.344024181366 this pink large cotton product is item.
21 1.3337094783783 pink extra-small cashmere product is product.

My question is :

id Relevance des
64 1.3543391227722 amazing pink petite lace item is item.
21 1.3337094783783 that pink extra-small cashmere product is product.

though having the same number of occurences:

column 64 has : item-2 times, pink-1 time and column 21 has : product-2 times pink-1 time.

Initial Thoughts

I thought the calculation is like this:

(refrence from MySQL FUll Text Search Doc, which says:)

${rank} = ${TF} * ${IDF} * ${IDF} + ${TF} * ${IDF} * ${IDF}

SELECT (1*log10(8/6)*log10(8/6)) + (2*log10(8/2)*log10(8/2));

which is :

(number of occurences of word 1* log10(total records in table/total matching records where the word is found) + (number of occurences of word 2* log10(total records in table/total matching records where the word is found) + ... + (number of occurences of word n * log10(total records in table/total matching records where the word n is found)

my question is how is the relevance calulated ?

also, even though column 64 and column 182 has same set of occureneces, both has pink-1 time and item-2 times, the relevance for column 64 is higher. why ?

initially i though this was based on row number in database, the order in which it was created. But in that case, my first question should be invalid as column 21 should come before column 64. I cant understand how it is calculated.

i did calculation this far with MySQL doc on full text search and i cant find a documnetation covering this kind of scenario.

Thanks in Advance.



via Chebli Mohamed

lundi 1 mai 2023

How to fix this issue "PHP Fatal error: Uncaught Error: Call to private PHPUnit\Framework\TestSuite::__construct() from scope"

I am facing below mentioned issue when executing the command "phpunit" in Lumen:

PHP Fatal error:  Uncaught Error: Call to private PHPUnit\Framework\TestSuite::__construct() from scope PHPUnit\TextUI\TestSuiteMapper in /usr/share/php/PHPUnit/TextUI/TestSuiteMapper.php:38
Stack trace:
#0 /usr/share/php/PHPUnit/TextUI/Command.php(390): PHPUnit\TextUI\TestSuiteMapper->map()
#1 /usr/share/php/PHPUnit/TextUI/Command.php(111): PHPUnit\TextUI\Command->handleArguments()
#2 /usr/share/php/PHPUnit/TextUI/Command.php(96): PHPUnit\TextUI\Command->run()
#3 /usr/bin/phpunit(73): PHPUnit\TextUI\Command::main()
#4 {main}
Next PHPUnit\TextUI\RuntimeException: Call to private PHPUnit\Framework\TestSuite::__construct() from scope PHPUnit\TextUI\TestSuiteMapper in /usr/share/php/PHPUnit/TextUI/Command.php:98
Stack trace:
#0 /usr/bin/phpunit(73): PHPUnit\TextUI\Command::main()
#1 {main}
  thrown in /usr/share/php/PHPUnit/TextUI/Command.php on line 98


via Chebli Mohamed