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.eyJleHAiOjE2ODU0ODUzOTMsImlhdCI6MTY4NTQ0OTM5MywianRpIjoiYWYxNTI5ZjAtNTdmYS00MjgyLWIzYTEtZWNlMzZlNjY4MzU2IiwiaXNzIjoiaHR0cHM6Ly9leHRhdX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vLnphL2F1dGgvcmVhbG1zL2ZpbmNsdWRlIiwic3ViIjoiZDNhNTNiZTgtZDgyOS00ZmU4LWI4ZmUtNGQzNDVkNzAzNWY4IiwidHlwIjoiUmVmcmVzaCIsImF6cCI6IkIyQl9BUEkiLCJzZXNzaW9uX3N0YXRlIjoiZTYxNzI3YzYtN2Y3YS00ODQyLTg4NGQtZTU3YWNlMmI3MzAxIiwic2NvcGUiOiJvcGVuaWQgcHJvZmlsZSByZWFkIHdyaXRlIn0.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 clicking

@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


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