mercredi 31 août 2022

i want to create directory with the name of the Company and i want to move some files related to that Company in that directory. How can i do it?

I successfully created the directories with this code in controller:

$cpath = public_path().'/files/completed/'.$file['customer_name'];
                if (! File::exists($cpath)) {
                    File::makeDirectory($cpath);
                }

but I am not sure how can i move related files to these directories for that I tried this:

File::move('files/pending/'.$filename,'files/completed/'.$file['customer_name'].$filename);

but the problem is I am not getting any files in their respective directories but the files are moving with the name renamed to (comapanyname filename.850) and that's not what I wanted here is how i am doing all the code in controller for directories and files:

 $cpath = public_path().'/files/completed/'.$file['customer_name'];
                if (! File::exists($cpath)) {
                    File::makeDirectory($cpath);
                }
       File::move('files/pending/'.$filename,'files/completed/'.$file['customer_name'].$filename);

Thank you for your response!



via Chebli Mohamed

i want to schedule one function in my controller every 5 minutes that is inserting files and product data in the DB.. how can i do that?

here is how data is updating in the DB with the page refresh but i want it to update automaticaaly after every 5 minutes so that without refreshing my data becomes visables on welcome page as well as the data is inserted automatically on function call(that should be after every 5 minutes). i am a beginner i tried to learn from laravel documentation but its not exactly displaying what i need.. your help will be appriciated... here is the code of how i am inserting data in the DB:

         foreach($files as $file){
            if (Invoice::where('file_name', '=', $file['file_name'])->exists()) {
            }
            else {
            $store = new Invoice;
            $store->file_name = $file['file_name'];
            $store->name = $file['customer_name'];
            $store->po_no = $file['po'];
            $store->address = $file['city'];
            $store->total_items = count($file['products']);
            $store->save();
            $invid = $store->id;

            for($x = 0; $x < count($file['products']); $x++)
            {
                $pstore = new InvoiceProduct;
                $pstore->product_name = $file['products'][$x];
                $pstore->invoice_id = $invid;
                $pstore->quantity =$file['count'][$x];
                $pstore->barcode=$file['scan'][$x];
                $pstore->vendor_code =$file['vn'][$x];
                $pstore->save();
             }
        }

and the function name is index i want to schedule this function every 5 minutes.. Thank you!



via Chebli Mohamed

lundi 29 août 2022

count where they don't have the same ID

i need to count all records in my table, but in the mp_id column there are repetitions

how to count only once where the content of mp_id is repeated?

so that the count is not wrong, i want the mp_id to count only once and not 3 or 4.

  $ingresos = Ingresosmp::All()->count('mp_id');

enter image description here



via Chebli Mohamed

Laravel response file problem in prevent back button history middleware

I am using Laravel, and I have created a PreventBack middleware to prevent users from returning to the page after logout.

Middleware

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class PreventBack
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        return $response->header('Cache-Control', 'no-cache, no-store,
                max-age=0, must-revalidate')
            ->header('Pragma', 'no-cache')
            ->header('Expires', 'Sun, 02 Jan 1990 00:00:00 GMT');
    }
}

But I have a route that returns the profile image.

Route::get('/profileimage', function () {

    return response()->file(storage_path('profile_image.jpg'));
});

When I put my profile image route in preventing back middleware, this route stops working, and the route does not return the profile image.

Route::group(['middleware' => ['PreventBack']], function () {
    Route::get('/profileimage', function () {
        return response()->file(storage_path('profile_image.jpg'));
    }); 
});


via Chebli Mohamed

Laravel: Version of Node

I'm running on a problem. My Laravel project is an old one, and I can't run npm run dev. Let's see some code:

php artisan laravel --version: Laravel Framework 5.8.38

node --version: v16.16.0 This is the actual version of Node installed

And the error when running NPM:

npm WARN npm npm does not support Node.js v16.16.0
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm Supported releases of Node.js are the latest release of 6, 8, 9, 10, 11.
npm WARN npm You can find the latest version at https://nodejs.org/

> @ dev /Users/marcellopato/Documents/Sites/webroker
> npm run development

npm WARN npm npm does not support Node.js v16.16.0
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm Supported releases of Node.js are the latest release of 6, 8, 9, 10, 11.
npm WARN npm You can find the latest version at https://nodejs.org/

> @ development /Users/marcellopato/Documents/Sites/webroker
> cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

node:events:505
      throw er; // Unhandled 'error' event
      ^

Error: spawn node_modules/webpack/bin/webpack.js ENOENT
    at Process.ChildProcess._handle.onexit (node:internal/child_process:283:19)
    at onErrorNT (node:internal/child_process:478:16)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)
Emitted 'error' event on ChildProcess instance at:
    at Process.ChildProcess._handle.onexit (node:internal/child_process:289:12)
    at onErrorNT (node:internal/child_process:478:16)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  errno: -2,
  code: 'ENOENT',
  syscall: 'spawn node_modules/webpack/bin/webpack.js',
  path: 'node_modules/webpack/bin/webpack.js',
  spawnargs: [
    '--progress',
    '--hide-modules',
    '--config=node_modules/laravel-mix/setup/webpack.config.js'
  ]
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ development: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the @ development script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/marcellopato/.npm/_logs/2022-08-29T14_40_33_577Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ dev: `npm run development`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the @ dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/marcellopato/.npm/_logs/2022-08-29T14_40_33_659Z-debug.log

The package.json:

    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
    },
    "devDependencies": {
        "axios": "^0.18.0",
        "bootstrap": "^4.1.3",
        "cross-env": "^5.2.0",
        "jquery": "^3.2",
        "laravel-mix": "^2.1.14",
        "lodash": "^4.17.11",
        "popper.js": "^1.14.3",
        "vue": "^2.5.16",
        "vuedraggable": "^2.16.0"
    },
    "dependencies": {
        "@tinymce/tinymce-vue": "^1.1.0",
        "@websanova/vue-upload": "^0.2.14-beta",
        "ajv": "^6.5.4",
        "jquery-filepond": "^1.0.0",
        "laravel-echo": "^1.4.0",
        "moment": "^2.22.2",
        "moment-timezone": "^0.5.21",
        "node-sass": "^4.9.4",
        "npm": "^6.4.1",
        "pusher-js": "^4.3.1",
        "tinymce-vue-2": "0.0.5",
        "v-calendar": "^0.9.7",
        "vlightbox": "^2.0.2",
        "vue-chat-scroll": "^1.2.0",
        "vue-google-charts": "^0.3.2",
        "vue-moment": "^4.0.0",
        "vue-scrollto": "^2.13.0",
        "vue-simple-lightbox": "^1.1.0",
        "vue-template-compiler": "^2.5.17",
        "vue-the-mask": "^0.11.1",
        "vue-toasted": "^1.1.25",
        "vue-upload-component": "^2.8.14",
        "vue-wysiwyg": "^1.7.2",
        "vue2-daterange-picker": "^0.1.1",
        "vue2-dropzone": "^3.5.2",
        "vue2-editor": "^2.6.1"
    }
}

I think the issue is relative to the actual version of Node, that is too new. Could be that? And if so, there's a way to know what version I had installed on my machine at the time I was working on the project for the first time?

Or the issue is a new one?



via Chebli Mohamed

jeudi 25 août 2022

how to use read value in laraval v5.2.2

this is information for the evrey coder if you have problem -xxxxxxxxxx

class Controller extends BaseController { use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;

//jojsososos public function file( ) { return view('file'); }

   public function upload_file(Request $request) {
   // echo "here";
   $path = 'C:\xampp\htdocs\demo_project\readme.md';
   $myfile = fopen($path, "r") or die("Unable to open file!");
   echo fread($myfile,filesize($path));
   fclose($myfile);             
   }


via Chebli Mohamed

mardi 23 août 2022

Is it possible to retrieve original filename from locally saved file in Laravel 5 that has been hashed

Is there a way possible to get the original file name of an already saved file that has been hashed into storage?

I can find hundreds of threads of how to get the original file name of the uploaded file, but these files have already been saved to disk with a hashed filename using $request->File->store()

My use case is that I want to create a controller that returns all saved images from disk, so the user can view them in the browser. I want to allow them to search on filenames, but all the filenames are hashed, and I can't work out how to find the original filename.

These files have not been saved into a database, they are simply sitting in the public images directory. I can use the Storage facade to retrieve Size and LastModified details, but nothing else.

Is it at all possible?



via Chebli Mohamed

lundi 22 août 2022

Undefined array key "project" - work with api, cteating console command

I have code where I use function for get data from api getTimeEntriesInfo

    public function getTimeEntriesInfo(int $user_id): array
    {
        $users = self::getAllData('time_entry', ['user_id'=>$user_id]);
        return $users['time_entries'];
    }

Then I create console command artisan to save all data from api:

<?php

class LinkNew extends Command
{

    public function handle()
    {
        $redmineService = new RedmineAPIService();
        $users = $redmineService->getUsersInfo();

        foreach ($users as $user) {
            $data = $redmineService->getTimeEntriesInfo($user['id']);
            //dd($data);

            $project = $redmineService->getTimeEntriesInfo($user['project']);
            $activity = $redmineService->getTimeEntriesInfo($user['activity']);
            $issue = $redmineService->getTimeEntriesInfo($user['issue']);
            $comments = $redmineService->getTimeEntriesInfo($user['comments']);

            if ($this->confirm('Is this information correct?')) {
                $link = new TimeEntry();

                $link->project = $project;
                $link->activity = $activity;
                $link->issue = $issue;
                $link->comments = $comments;
                //dd($link->getAttributes());
                $link->save();

                $this->info("Saved.");
            }
        }
        return 0;
    }
}

But I have mistake Undefined array key "project". Why?

dd($data)

  248 => array:10 [
    "id" => 5379
    "project" => array:2 [ …2]
    "issue" => array:1 [ …1]
    "user" => array:2 [ …2]
    "activity" => array:2 [ …2]
    "hours" => 1.5
    "comments" => "Some comment"
    "spent_on" => "2022-05-27"
    "created_on" => "2022-05-27T09:31:18Z"
    "updated_on" => "2022-05-27T09:31:18Z"
  ]
  249 => array:10 [
    "id" => 5369
    "project" => array:2 [ …2]
    "issue" => array:1 [ …1]
    "user" => array:2 [ …2]
    "activity" => array:2 [ …2]
    "hours" => 1.0
    "comments" => "Some comment"
    "spent_on" => "2022-05-27"
    "created_on" => "2022-05-27T05:00:19Z"
    "updated_on" => "2022-05-27T05:00:19Z"
  ]

upd

    public function handle()
    {
        $redmineService = new RedmineAPIService();
        $users = $redmineService->getUsersInfo();
        foreach ($users as $user) {
            $data = $redmineService->getTimeEntriesInfo($user['id']);


            //isset($user);
            foreach ($users as $user) {
                //$data = $redmineService->getTimeEntriesInfo($user['id']);
                //dd($data);

                $project = $data['project'];
                $activity = $redmineService->getTimeEntriesInfo($data['activity']);
                $issue = $redmineService->getTimeEntriesInfo($data['issue']);
                $comments = $redmineService->getTimeEntriesInfo($user['comments']);

                if ($this->confirm('Is this information correct?')) {
                    $link = new TimeEntry();

                    $link->project = $project;
                    $link->activity = $activity;
                    $link->issue = $issue;
                    $link->comments = $comments;
                    //dd($link->getAttributes());
                    $link->save();

                    $this->info("Saved.");
                }
            }
        }

        return 0;
    }


via Chebli Mohamed

dimanche 21 août 2022

fetch maximum column row in laravel

I have this table structure

id |  user_id  |   sequence_id  |  test_id

1       11             1            4
2       11             3            4
3       11             9            4
4       11            10            4

..
..
20      11             18           4

i want to fetch the maximum sequence_id that exist for particular user, using this query

test::where('test_id', $request->id)->orderBy('sequence_id', 'DESC')->get();

but getting 9th sequence id but it should return 18

Any solution Thanks



via Chebli Mohamed

Exception in UI \ view in section that is in comment - HTML PHP Laravel

I have a question, and I am new to laravel and html. I have a view, and in the view I have a certain code that is in comment. when I try to load the page it throws exception on this part of code, But why? If I remove the code completely it worked, so why the page loads the comments?

this the code:

 <!--  <td> Removed in and not to use
                    <input type="text" class="table-control p-r-20" name="dsp_fee_pct" value="" id="dsp_fee_pct">
                    <span class="table-control-addon-right">%</span>
                </td> -->

and this is the exception: enter image description here



via Chebli Mohamed

vendredi 19 août 2022

Generate PDF with image from database with mPDF Laravel

I have an issue with a view and generated content to produce a PDF.At the moment, I've been working with mpdf\mpdf , but when i want to show the image on the view , error occurs .

My controller :

$view = View::share('data', $data);
$mpdf= new \Mpdf\Mpdf([
            'mode'=>'UTF-8','format' => [400, 400],'autoScriptToLang'=>true,'autoLangToFont'=>true
]);
$mpdf->WriteHTML(view('frontend.create-cv.pdf',compact('data')));

My blade :

<img src="/frontend/assets/images/cv/">


via Chebli Mohamed

Get specific values from same table after Group By

Hi pls check the below Query

SELECT * FROM order_has_status group by order_id order by order_id DESC;

query_result

I'm trying to get the marked orders_id



via Chebli Mohamed

jeudi 18 août 2022

How to prevent HTML resizing in PDF using mPDF and Laravel?

This is my original HTML page :

original HTML

And this the output of generated PDF :

generated PDF

In the parts marked with a red arrow in the last picture, the size of the elements decreases automatically . How can I prevent this?



via Chebli Mohamed

mercredi 17 août 2022

Laravel Eloquent Relationship query with whereHas retrieve data

I have the following models in my application(Laravel):

class City extends Model {
  public function travels(){
    return $this->belongsToMany('App\models\Travel');
  }
}

class Travel extends Model {
   public function cities(){
     return $this->belongsToMany('App\models\City');
   }
   public function deals(){
     return $this->hasMany('App\models\Deal');
   }
}

I have the following table layout:

cities:

  • id
  • name

travels:

  • id
  • description

city_travel:

  • id
  • city_id
  • travel_id

deals:

  • id
  • travel_id

Now I want to display all the names of the cities with the count of travels where have deals (I not only want the cities which have only travels but these travels must also have deals) I hope I have explained my need well.

I tried only to retrieve the cities that have travels, with the code below but I'm stuck here :

$cities = City::whereHas('travels')-get();

Thanks for your help!



via Chebli Mohamed

How I can convert a dynamic blade content into PDF with mPDF in Laravel 7?

This my frontend.create-cv.pdf.blade.php :

<section>

    <h1>Language</h1>

    @foreach ($data['languages'] as $lang)

        <em> | </em>

    @endforeach

</section>

And this is my controller :

$data['languages'] = language_skill::where('jobseeker_id', $id)->get();

$mpdf->WriteHTML(view('frontend.create-cv.pdf', ['data' => $data]));

I'm geting this error :

Undefined variable: data (View: E:\xampp\htdocs\rzgroup.az\resources\views\frontend\create-cv\pdf.blade.php)`

How can i solve this problem ?



via Chebli Mohamed

mardi 16 août 2022

I received email with subject LARAVEL SMTP CRACK | HOOST

Today i get email with subject "LARAVEL SMTP CRACK | HOOST" I use laravel framework 5.8. My .env include

APP_ENV = production
APP_DEBUG = false

and

MAIL_DRIVER=smtp
MAIL_HOST=smtp.domain.site
MAIL_PORT=2525
MAIL_USERNAME=xxx
MAIL_PASSWORD=xxxx
MAIL_ENCRYPTION=tls

what can i do ? was my site hacked?



via Chebli Mohamed

lundi 15 août 2022

Laravel v5.5 echo doesn't catch event and pusher doesn't broadcast event

I am currently unable to BOTH listen to events or use the pusher to broadcast events.

Issue

  1. I have the payload messages being generated in laravel log but it doesnt appear on the pusher debugging site.

  2. In terms of receiving the event, the echo listener doesn't get triggered when a message is sent on the pusher debugging site although there I am already subscribed to it. enter image description here

Front End (Echo)

 $(document).ready(function() {
            window.Echo.private('scannedUpdate')
            .listen('scannedQR', (e) => {
                console.log("fight back");
                alert('fight back');
            });
        });

Event

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
class scannedQR implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $username;
    public $message;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($username)
    {
        error_log("Made it");
        $this->username = $username;
        $this->message = $username . " has scanned qr code";
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        error_log("Entered broadcast on");
        return new PrivateChannel('scannedUpdate');
        
        // return 'scannedQR';
    }

    public function broadcastAs()
    {
        error_log("In broadcast as");
        return 'scannedQR';
    }
}

Route (Trigger Event)

Route::get('/chatbot/test', function () {
    broadcast(new scannedQR('Cheese'));
    return "Event has been sent!";
});

Laravel Log

local.INFO: Broadcasting [scannedQR] on channels [private-scannedUpdate] with payload:
{
    "username": "Cheese",
    "message": "Cheese has scanned qr code",
    "socket": null
}  

Bootstrap.js

import Echo from 'laravel-echo'

window.Pusher = require('pusher-js');

window.Lover = "LOVER!";

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'key',
    // cluster: 'mt1',
    cluster:'ap1',
    encrypted: true
});

Channels (Never gets called)

Broadcast::channel('scannedUpdate', function ($user) {
    error_log("Within channel");
    return true;
});


via Chebli Mohamed

mercredi 10 août 2022

How to Mock environment in Laravel 5.7

I'm trying to implement a unit test in Laravel 5.7 I want to mock APP_ENV testing to production or any else as I want.

Unit test code:

App::shouldReceive('environment')->with('APP_ENV')->once()->andReturn('production');

Code:

if (in_array(env('APP_ENV'), ["production", 'local'])) {
    return "This production environment";
}

There was 1 error:

Mockery\Exception\BadMethodCallException: Received Mockery_5_Illuminate_Foundation_Application::offsetGet(), but no expectations were specified


via Chebli Mohamed

created_at and updated_at columns not updated by updateorcreate - Laravel Eloquent

Hey All I am new to Laravel. I have a table called dsp_account_fee. enter image description here enter image description here

This is what I have in my Model.

{
    use AdvancedInserts;

    protected $table = "dsp_account_fee";
    protected $primaryKey = 'dsp_account_id';
    protected $secondaryKey = 'screen_type';


    public $timestamps = false;

    protected function setKeysForSaveQuery(Builder $query)
    {
        parent::setKeysForSaveQuery($query);
        $query->where($this->secondaryKey, '=', $this->{$this->secondaryKey});
        return $query;
    }

    protected $fillable = array(
        'dsp_account_id', 'screen_type', 'pmp_percent' , 'omp_percent'
    );

}

When I create or update record I use the updateorcreate method like this:

$res1 = DspAccountFee::updateOrCreate(
                ['dsp_account_id' => $dsp_account_id, 'screen_type' => 'ctv'],
                ['pmp_percent' =>$fields['fee_ctv_pmp_percent'], 'omp_percent' => $fields['fee_ctv_omp_percent']]
                );

The problem is that the created_at and the updated_at not filled automatically and stay null. what I am missing?



via Chebli Mohamed

UpdateOrCreate not updating data - Laravel Eloquent

I am new to laravel. I have an issue when I am trying to update or create record in DB. I have a table called DspAccountFee with this columns: enter image description here

I want to create record of dsp_account_id + screen_type when the combination not exists, and to update if the combination exists. this is my code: (just tried to update the first row keys of -> dsp_account_id(5187) + screen type (ctv). However nothing changed.

DspAccountFee::updateOrCreate(
                ['dsp_account_id' => $dsp_account_id, 'screen_type' => 'ctv'],
                ['pmp_percent' =>$fields['fee_ctv_pmp_percent'], 'omp_percent' => $fields['fee_ctv_omp_percent']]
                );

When I print the values before the DB operation they exists:

\Log::info("dsp_account:");
\Log::info($dsp_account_id);
\Log::info("ctv pmp percent:");
\Log::info($fields['fee_ctv_pmp_percent']);
\Log::info("ctv omp percent:");
\Log::info($fields['fee_ctv_omp_percent']);
\Log::info("app pmp percent:");

enter image description here

What I am missing why it is not update the db? Nothing in logs and No exception

this is my method in the model

protected $fillable = array(
        'dsp_account_id', 'screen_type'
    );


via Chebli Mohamed

lundi 8 août 2022

Google Authentication Login in Laravel 5.4

Client error: GET https://www.googleapis.com/plus/v1/people/me?prettyPrint=false resulted in a 403 Forbidden response: { "error": { "code": 403, "message": "Legacy People API has not been used in project 536929073653 before or it (truncated...) enter image description here



via Chebli Mohamed

Laravel 5.8 How to create a validation "if availability = "in stock" the quantity must be greater than 0 - Stack Overflow

Add validation for column quantity, if availability column equals to "in stock", the quantity column should be greater than 0.



via Chebli Mohamed

dimanche 7 août 2022

Laravel Generate key for decrypt password

I am working on a code

if (!function_exists('decrypt_password')) {
    function decrypt_password( $iv, $value)
    {
        $key = config('services.decrypt.key');

        $string_iv =hex_to_string($iv);
        $encrypter = new Encrypter($key, 'AES-256-CBC');

        $dec['iv'] = base64_encode($string_iv);
        $dec['value'] = $value;
        $dec['mac'] = hash_hmac('sha256',  $dec['iv'] . $dec['value'], $key);
       
        return ($encrypter->decrypt(base64_encode(json_encode($dec)),false));
    }
}

this piece of code should make a layer of decrypting the password, and key is missing in config and I can't get one or generate a new one. any help!



via Chebli Mohamed

samedi 6 août 2022

Custom legend in Chart [duplicate]

i am using xcosta/laravel-chartjs to generate chart. In the docs there is no mention of legendcallback:function(){}. i want to generate custom legend but am being unable to generate. Can someone help me on this one.



via Chebli Mohamed

vendredi 5 août 2022

HTTP ERROR 500? is currently unable to handle this request? [closed]

/home/maxmpgdb/public_html/vendor/laravel/framework/src/Illuminate/View/Engines/CompilerEngine.php(61): Illuminate\View\Engines\PhpEngine->evaluatePa in /home/maxmpgdb/public_html/resources/views/themes/royalblue/partials/footer.blade.php on line 58enter image description here



via Chebli Mohamed

jeudi 4 août 2022

Laravel permissions pivot table

I am making custom permissions,

I would like them to be divided into sections e.g. orders, customers etc. and each section would have some permission e.g. edit, delete, add. Just to check if a particular user has access I would have to start with the Section model?

Because I can't do something like Auth::user()->permissions()->with('sections')->contains('name','display')->contains('sections','order')

I would like to simply check if the user has access to, for example, order.display. I have a feeling that this section does not make sense here.

How to do it? I know there is a spatie(laravel-permission), but there is a role division there.

Example schema of the database (user_permission is a pivot): enter image description here



via Chebli Mohamed

How to export currently searched data in excel laravel?

I am trying to exceldownload only the data searched by the user but my code isnt working.

Controller

 public function get_data(Request $request, Covidrecord $covidrecord)
{
    $search = $request['search'] ?? '';
    if ($search != '') {
        $covidrecord = Covidrecord::where('fullname', 'LIKE', "%$search%")
            ->orWhere('gender', 'LIKE', "%$search%")
            ->orWhere('age', 'LIKE', "%$search%")
            ->orWhere('hospital_type', 'LIKE', "%$search%")
            ->orWhere('vaccine_status', 'LIKE', "%$search%")
            ->get();
    }
   
       Excel::create('covidrecord', function($excel) use($covidrecord) {
                   $excel->sheet('sheet 1', function($sheet) use($covidrecord){
                       $sheet->fromArray($covidrecord);
                   });
       })->download('xlsx');

}

Below is the Export.php..How can i filter search here??

CovidRecordExport.php

class CovidRecordExport implements FromCollection
{
   
    public function headings():array{
        return[
            'fullname',
            'age',
            'gender',
            'ethinicity',
            'religion',
            'occupation',
            'qualification',
            'financial_status',
            'marital_status',
            'infection_date',
            'covid_verficiation',
            'hospitalization_date',
            'hospital_type',
            'death_date',
            'death_reason',
            'after_covid_death',
            'death_location',
            'vaccine_status',
            
        ];
    }
    public function collection()
    {
        return CovidRecord::all();
    }
}

I tried dd() and it seems like my if condition is not working.



via Chebli Mohamed

mardi 2 août 2022

"Invalid argument supplied for foreach()", in laravel controller

I want to add coupon code system in e commerce website using laravel 5.8 when i click on apply coupon button it gives me error like "Invalid argument supplied for foreach()" the problem is with that foreach loop in my controller when i remove it then it shows 0 price can anybody help me to solve this problem

here is my controller

   public function applycoupon(Request $request){
    $coupon = $request->input('coupon_code');
    if(Coupons::where('coupon_code',$coupon)->exists())
    {
      $coupon = Coupons::where('coupon_code',$coupon)->first();
     if($coupon->start_date<=Carbon::today()&& Carbon::today()<= $coupon->end_date){
        $totalprice = "0";
        $cookie_data = stripslashes(Cookie::get('shoping_cart'));
        $cart_data = json_decode($cookie_data,true);
        foreach ($cart_data as $itemdata){
            $product = Product::find($itemdata['item_id']);
            $prod_price = $product->offer_price;
           // $prod_price_tax = ($prod_price*$product->tax)/100;
            $totalprice = $totalprice+($itemdata['item_quantity']*$prod_price);
        }

        //checking Type (percentage or amount)
       if($coupon->coupon_type=='Percentage')
       {
        $discount_price = ($totalprice/100)*$coupon->coupon_price;
       }
       elseif($coupon->coupon_price=='amount'||'Amount')
       {
         $discount_price = $coupon->coupon_price;
       }
       $grand_total = $totalprice-$discount_price;
       return response()->json([
         'discount_price' =>$discount_price,
          'grand_total' =>$grand_total,
       ]);
     }
     else
     {
     return response()->json([
        'status'=> 'coupon code has been expired',
        'error_status'=>'error'
      ]);
      }
    }
    else
    {
        return response()->json([
            'status'=> 'coupon code does not exists',
            'error_status'=>'error'
          ]); 
    }
}

views.blade file

 <div class="card-body">
                    <div class="d-flex justify-content-between mb-3 pt-1">
                        <h6 class="font-weight-medium">Subtotal</h6>
                        <h6 class="font-weight-medium">$</h6>
                    </div>
                    <div class="d-flex justify-content-between">
                        <h6 class="font-weight-medium">Discount</h6>
                        <h6 class="font-weight-medium discount_price">0.00</h6>
                    </div>
                </div>

Route

Route::post('apply-coupons','CouponController@applycoupon');

custom js file

custom js file

    //Apply coupons
$(document).ready(function () {
    $('.apply-coupon-btn').click(function (e) {
        e.preventDefault();
        var coupon_code = $('.coupon_code').val();
        if ($.trim(coupon_code).length == 0) {
            error_coupon = "please enter valid coupon";
            $('#error_coupon').text(error_coupon);
        } else {
            error_coupon = "";
            $('#error_coupon').text(error_coupon);
        }
        if (error_coupon != '') {
            return false;
        }
        $.ajax({
            method: "POST",
            url: "/apply-coupons",
            data: {
                'coupon_code': coupon_code,
            },
            success: function (response) {
                if (response.error_status == 'error') {
                    alertify.set('notifier', 'position', 'top-right');
                    alertify.success(response.status);
                    $('.coupon_code').val('');
                }
                else{
                    var discount_price = response.discount_price;
                    var grand_total = response.grand_total;
                    $('.discount_price').text(discount_price);
                    $('.grand_total').text(grand_total);
                }
            }
        });

    });
});


via Chebli Mohamed