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!



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/CiaYSqK
via IFTTT

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!



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/ZHCSjB2
via IFTTT

mardi 30 août 2022

Laravel Project not run on http mode but run in https [closed]

Hello my issue is about my project not to be run on http mode.

they show me an error like "419 PAGE EXPIRED"

plz share a perfect solution also describe the reason.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/xqjNpAG
via IFTTT

General error: 11 database disk image is malformed [closed]

i have a problem. I would like to know why when I upload a csv file in laravel I get this error? General error: 11 database disk image is malformed



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/QLkYgpV
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/arglXqI
via IFTTT

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'));
    }); 
});


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/BcUDqtz
via IFTTT

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/haTYb7j
via IFTTT

vendredi 26 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);             
   }


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/cGdn6D8
via IFTTT

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/5DenO7u
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/TzIMQH4
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/lC8dcIe
via IFTTT

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/">


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/a4fD3Ec
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/IFJv69x
via IFTTT

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/Gc5NI8w
via IFTTT

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!



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/wEZ7BvD
via IFTTT

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 ?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/RWz5AUt
via IFTTT

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/O9m0WdR
via IFTTT

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;
});


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/BVKNSc1
via IFTTT

mercredi 10 août 2022

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/1TjM0UI
via IFTTT

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'
    );


from Newest questions tagged laravel-5 - Stack Overflow https://stackoverflow.com/questions/73304080/updateorcreate-not-updating-data-laravel-eloquent
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/Jwc6noX
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/wZvqOkC
via IFTTT

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!



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/A2ycxl9
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/zsyxjM1
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/ZYOaUQr
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/oIEAx5e
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/rxQNXY5
via IFTTT

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);
                }
            }
        });

    });
});


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/g1WkEc0
via IFTTT

lundi 1 août 2022

PHP add minutes to MongoDB\BSON\UTCDateTime

use MongoDB\BSON\UTCDateTime;

$date = new UTCDateTime($val * 1000); // 1659356187861

How can I do this if I want to subtract or add 5 minutes from this $date variable?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/jzC1Hn3
via IFTTT

Laravel SwitMessage add Reply-path header

We have a Laravel application which sends newsletters to customers. As per the client's request, we would like to add a header in the email indicating that it's a newsletter or mail to a list to avoid out of office email bounces. Upon research, I found that one way to do so is to add Precedence: bulk header. But answer also says that RFC 2076 discourages adding Precedence header. Some post recommend adding Return-Path: <> (a NULL Return-Path). However, I'm not able to add this header. I have tried following codes to add such a header but not working.

$headers->addTextHeader('Return-Path', ''); - Uses the mail id defined in config file 
$headers->addTextHeader('Return-Path', '<>') - This generates a malformed header as in the attached image
$headers->addTextHeader('Return-Path', ' '); - Adds a header like Return-Path   
< > but not sure if this is correct or it will create other issues


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/Hi3ILUB
via IFTTT