PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label laravel. Show all posts
Showing posts with label laravel. Show all posts

Monday, December 5, 2022

[FIXED] Why SELECT table with 200.000 records is using too much memory (+2GB)?

 December 05, 2022     laravel, oci8, php     No comments   

Issue

I'm selecting data from a VIEW in Oracle that in real size is around 50MB (61 columns and 263.000 rows). I only have one column with data length of 4000 and all others up to 100.

When I selecting using Laravel (split into packages of 10.000 records) it is occupying around 2.5GB in memory.

I have made some search and tried disable log queries using DB::disableQueryLog, $connection->disableQueryLog(), included gc_collect_cycles call after each SELECT and unset the results variable - without any effect.


<?php

use Yajra\Oci8\Connectors\OracleConnector;
use Yajra\Oci8\Oci8Connection;

/**
 * @return Oci8Connection
 * @throws \Exception
 */
private function getOracleConnection()
{
    $config = [
        'driver' => 'oracle',
        'host' => 'host',
        'database' => 'database',
        'port' => 'port',
        'username' => 'user',
        'password' => 'password',
        'charset' => 'charset',
        'schema' => 'schema',
        'options' => [
            \PDO::ATTR_PERSISTENT => true
        ],
    ];
    $connector = new OracleConnector();
    $connection = $connector->connect($config);

    $db = new Oci8Connection($connection, $database);

    return $db;
}

protected function loadSourceSystemData(): Collection
{
    $connection = $this->getOracleConnection();

    DB::disableQueryLog();
    $connection->disableQueryLog();

    $package_size = 10000;

    $return = new Collection();
    $offset = 0;

    while(true) {
        $records = $connection->query()
            ->from('ZVPCP003')
            ->take($package_size)
            ->offset($offset)
            ->get();

        if(empty($records)) break;

        $return = $return->merge($records);
        unset($records);

        gc_collect_cycles();
        $offset += $package_size;
    }

    return $return;
}

My expectation is using less then 1GB at least, that is very high yet but is acceptable.

Update: I have measured the real memory use:

Rows: 10000 | Mem: 124 MB  
Rows: 20000 | Mem: 241 MB  
Rows: 30000 | Mem: 357 MB  
Rows: 40000 | Mem: 474 MB  
Rows: 50000 | Mem: 590 MB  
Rows: 60000 | Mem: 707 MB  
Rows: 70000 | Mem: 825 MB  
Rows: 80000 | Mem: 941 MB  
Rows: 90000 | Mem: 1058 MB  
Rows: 100000 | Mem: 1174 MB  
Rows: 110000 | Mem: 1290 MB  
Rows: 120000 | Mem: 1407 MB  
Rows: 130000 | Mem: 1523 MB  
Rows: 140000 | Mem: 1644 MB  
Rows: 150000 | Mem: 1760 MB  
Rows: 160000 | Mem: 1876 MB  
Rows: 170000 | Mem: 1993 MB  
Rows: 180000 | Mem: 2109 MB  
Rows: 190000 | Mem: 2226 MB  
Rows: 200000 | Mem: 2342 MB  
Rows: 210000 | Mem: 2459 MB  
Rows: 220000 | Mem: 2575 MB  
Rows: 230000 | Mem: 2691 MB  
Rows: 240000 | Mem: 2808 MB  
Rows: 250000 | Mem: 2924 MB  
Rows: 260000 | Mem: 3041 MB  
Rows: 263152 | Mem: 3087 MB  

Solution

Maybe by converting loadSourceSystemData to generator and then process data in chunks, this way you will have at most 10000 rows loaded at time, since they are not collected to one big collection they can be automatically freed.

<?php

function loadSourceSystemData(): iterable
{
    $connection = $this->getOracleConnection();
    DB::disableQueryLog();
    $connection->disableQueryLog();
    $package_size = 10000;
    $offset = 0;
    do {
        $records = $connection->query()->from('ZVPCP003')
                ->take($package_size)
                ->offset($offset)
                ->get();
        $offset += $package_size;
        yield collect($records);
    } while(!empty($records));
}

foreach($this->loadSourceSystemData() as $collection) {
    foreach($collection as $row) {
        // Process row here
    }
}

Update

I've tried to load data from CSV file to check overhead and when using arrays it takes about 70% more memory then using objects.

For 500000 rows like "P80,A142900,2012,6,35" array took about 213MB while array of objects 136 MB.

class Item {
    public $a;
    public $b;
    public $c;
    public $d;
    public $e;
}

if (($handle = fopen("data.csv", "r")) !== FALSE) {
    $row = 0;
    $list = [];
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $item = new Item();
        $item->a = $data[0];
        $item->b = $data[1];
        $item->c = $data[2];
        $item->d = $data[3];
        $item->e = $data[4];
        $list[] = $item;
        //$list[] = $data;
    }
    fclose($handle);
    $m = memory_get_usage(true) / 1000 / 1000;
    echo "Rows ", count($list), " Memory ", $m, "MB \n";
}

Update 2

More memory can be saved if data is converted to specific types eg. int and if some columns have lot's of repeating value then caching can be used.

class Name {
    public $name;
    public function __construct($name)
    {
        $this->name = $name;
    }
}

class NameCache {
    private $cache = [];
    public function getName(string $name) {

        if (isset($this->cache[$name])) {
            return $this->cache[$name];
        }
        $item = new Name($name);
        $this->cache[$name] = $item;
        return $item;
    }
}

$nameCache = new NameCache();
$item = new Item();
$item->a = $nameCache->getName($data[0]);
$item->b = $nameCache->getName($data[1]);
$item->c = (int)$data[2];
$item->d = (int)$data[3];
$item->e = (int)$data[4];

With this memory was reduced from 136MB to 75MB.



Answered By - Edin Omeragic
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to know laravel connect with Oracle oci8 and select statment write

 December 05, 2022     laravel, oci8, oracle, yajra-datatable     No comments   

Issue

Here is my Code in laravel with Oci8. i get this result

oci8 statement resource @364

. does anyone know what is issue? how to connect and use select statement.

$users = oci_connect('LE2', 'LE2', '(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = 10.10.55.5)(PORT = 1521)) (CONNECT_DATA = (SERVICE_NAME = ORCL)))');
        if (!$users) {
            dd("no coonection");

          }else{
            $ss = oci_parse($users, "SELECT * FROM v_doctor_list");
            dd($ss);
          }

Solution

use yajra library to connect laravel to oracle you can use this code to test connection

if (DB::connection('your-connection-name')->getDatabaseName()) {
    echo "connected" 
}else{
 echo "not connected" 
}


Answered By - waleedazam
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, December 3, 2022

[FIXED] How to set X-Frame-Options in laravel project?

 December 03, 2022     clickjacking, html, iframe, laravel, websecurity     No comments   

Issue

I want to prevent my website from clickJacking attack. In which file and where to set X-Frame-Options for preventing clickJacking attack.


Solution

You have 2 ways:

  • Setup it in a reverse proxy such as Nginx
add_header X-Frame-Options "SAMEORIGIN";
  • Use Laravel middleware Illuminate\Http\Middleware\FrameGuard onto the routes you want to protect.
<?php

namespace Illuminate\Http\Middleware;

use Closure;

class FrameGuard
{
    /**
     * Handle the given request and get the response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        $response->headers->set('X-Frame-Options', 'SAMEORIGIN', false);

        return $response;
    }
}


Answered By - Shizzen83
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, November 23, 2022

[FIXED] How to get phpstan to infer the type for my Laravel Collection pipeline?

 November 23, 2022     illuminate-container, laravel, php, phpstan     No comments   

Issue

Given my class

<?php
declare(strict_types=1);

use Illuminate\Support\Collection;
use stdClass;

class PhpstanIssue
{
    /**
     * @param Collection<Collection<stdClass>> $collection
     *
     * @return Collection<Foo>
     */
    public function whyDoesThisFail(Collection $collection): Collection
    {
        return $collection
            ->flatten() // Collection<stdClass>
            ->map(static function (\stdClass $std): ?Foo {
                return Foo::get($std);
            }) // should now be Collection<?Foo>
            ->filter(); // should now be Collection<Foo>
    }
}

I am highely confused why phpstan (0.12.64) would fail with:

18: [ERROR] Method PhpstanIssue::whyDoesThisFail() should return
Illuminate\Support\Collection&iterable<Foo> but returns 
Illuminate\Support\Collection&iterable<Illuminate\Support\Collection&iterable<stdClass>>. (phpstan)

Why can't phpstan infer the proper result type of this pipe? How can I make phpstan understand the pipe?


I can verify that my code works within a phpunit testcase:

class MyCodeWorks extends TestCase
{
    public function testPipeline()
    {
        $result = (new PhpstanIssue())->whyDoesThisFail(
            new Collection(
                [
                    new Collection([new \stdClass(), new \stdClass()]),
                    new Collection([new \stdClass()]),
                ]
            )
        );

        self::assertCount(3, $result);
        foreach ($result as $item) {
            self::assertInstanceOf(Foo::class, $item);
        }
    }
}

will pass.


My Foo is just a dummy class for the sake of this question. It's only relevant that it takes a stdClass instance and transforms it into a ?Foo one.

class Foo
{
    public static function get(\stdClass $std): ?Foo
    {
        // @phpstan-ignore-next-line
        return (bool) $std ? new static() : null;
    }
}


Solution

Illuminate\Support\Collection class is not generic on its own. So writing Collection<Foo> is wrong. That causes the error messages like Illuminate\Support\Collection&iterable<Illuminate\Support\Collection&iterable<stdClass>>

You have two options:

  1. Installing Larastan. It's a PHPStan extension for Laravel. And it has stub files that makes Illuminate\Support\Collection class generic.

  2. Or if you are just using the illuminate/collections standalone package without full Laravel app you can write your own stub files. From PHPStan docs:

... you can write a stub file with the right PHPDoc. It’s like source code, but PHPStan only reads PHPDocs from it. So the namespace and class/interface/trait/method/function names must match with the original source you’re describing. But method bodies can stay empty, PHPStan is only interested in the PHPDocs.

For your example the following stub file should be enough:

<?php

namespace Illuminate\Support;

/**
 * @template TKey
 * @template TValue
 * @implements \ArrayAccess<TKey, TValue>
 * @implements Enumerable<TKey, TValue>
 */
class Collection implements \ArrayAccess, Enumerable
{
    /**
     * @template TReturn
     * @param callable(TValue, TKey): TReturn $callable
     * @return static<TKey, TReturn>
     */
    public function map($callable) {}
}


Answered By - Can Vural
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why do I get error when try to convert Carbon to DateTime?

 November 23, 2022     laravel, php, php-carbon, phpstan     No comments   

Issue

I am developing a Laravel project. I try to create a DateTime object by using Carbon. This is what I tried:

Carbon::createFromFormat('Y-m-d H:i:s', '2021-10-01T00:01:00')->toDateTime();

But my phpstan complains : Cannot call method toDateTime() on Carbon\Carbon|false.

Why is this error? What is the correct way to convert Carbon to a DateTime object?


Solution

Your format is incorrect, so Carbon cannot create the time. You're missing the T, which needs to be escaped.

Carbon::createFromFormat('Y-m-d\TH:i:s', '2021-10-01T00:01:00')->toDateTime();


Answered By - aynber
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, November 22, 2022

[FIXED] How to disable warning for specific exceptions?

 November 22, 2022     exception, laravel, phpstan, phpstorm     No comments   

Issue

I do get a warning whenever I throw an exception in my code without explicitly stating it in the docblocs: enter image description here

I know this can be fixed by adding @throw tags, but the warning is actually not 100% true, as I do handle the exception in /app/Exceptions/Handler.php. I would like to disable the warning for this single exception. Is this possible in PHPStan? I have not found anything in the docs, but in this blog post https://phpstan.org/blog/bring-your-exceptions-under-control it seems that one can have unchecked & checked exceptions, and I believe unchecked exceptions do not need to be declared. However, marking my exception unchecked in phpstan.neon does not get rid of the error:

 exceptions:
        uncheckedExceptionClasses:
            - 'app\Exceptions\AuthenticationException'

I also noticed that the Symfony\Component\HttpKernel\Exception\NotFoundHttpException exception does not trigger the warning. I am not sure why, but it seems there is already a set of exceptions where no @throw is needed.

enter image description here

How can I suppress the warning for my exception?


Solution

As Bob has correctly stated this comes from PhpStorm itself and not PHPStan.

You can add any exception to the Unchecked Exception list so it will be ignored by PhpStorm at Settings/Preferences | PHP | Analysis

https://www.jetbrains.com/help/phpstorm/php-missing-throws-tag-s.html

enter image description here


As to why Symfony\Component\HttpKernel\Exception\NotFoundHttpException is not reported -- they have different parents:

  • NotFoundHttpException extends HttpException extends \RuntimeException (which is in unchecked list)
  • AuthenticationException extends \Exception


Answered By - LazyOne
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to complete pending transactions in paypal payouts

 November 22, 2022     laravel, paypal, php     No comments   

Issue

I am trying to implement a single Payout functionality in Paypal. I have referred to the sample code given by Paypal's documentation here. Everything seems to be working in order but the response given by PayPal indicates this: "batch_status": "PENDING". Here is my payout function:

public function payoutWithPaypal()
{
    $request_amount = session()->get('request_amount');
    $transaction_id = session()->get('transaction_id');
    $receiver_email = session()->get('receiver_email');

    $payouts = new \PayPal\Api\Payout();
    $senderBatchHeader = new \PayPal\Api\PayoutSenderBatchHeader();
    $senderBatchHeader->setSenderBatchId(uniqid())->setEmailSubject("You have a Payout!");
    $senderItem = new \PayPal\Api\PayoutItem();
    $senderItem->setRecipientType('Email')
                ->setNote('Thanks for your patronage!')
                ->setReceiver($receiver_email)
                ->setSenderItemId("001")
                ->setAmount(new \PayPal\Api\Currency('{
                            "value":"'.$request_amount.'",
                            "currency":"USD"
                        }'));

    $payouts->setSenderBatchHeader($senderBatchHeader)->addItem($senderItem);
    $request = clone $payouts;
    
    try {
        $output = $payouts->create(array('sync_mode' => 'false'), $this->_api_context);

    } catch (\Exception $ex) {
         dd($ex);
    }

    return $output;

}

The solutions provided here have not really solved my issue.


Solution

Payouts run in a batch. For a batch status to begin as 'PENDING' is normal. The status of each payout within the batch is what matters. You can query them as needed, and if they are individually pending some reason may be given.

The most common reason for a PayPal payment to be pending in sandbox or live is if there is no PayPal account with a confirmed email (in sandbox or live, respectively) at the address to which the payment was sent. Receivers have 30 days to create an account and/or confirm the email on their account to accept the payment, otherwise it will be automatically refunded after 30 days. Reminders are sent to that email during this period.



Answered By - Preston PHX
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, November 20, 2022

[FIXED] How to delete the first digit number in PHP

 November 20, 2022     laravel, php, preg-replace, regex, regex-negation     No comments   

Issue

I have a data of phone number starts with +63 and 09

for example the user insert 09123456789 then save. The user shouldn't success if he enters +639123456789 because it was same number at all.

I tried using substr_replace

$data3 = substr_replace("+63", "0",0, 3);

is there other option? i think the substr_replace will have error in the future.

thanks


Solution

If the +63 must be at the start, you may use a preg_replace like

$s = preg_replace('~^\+63~', '0', $s);

Here,

  • ^ - start of a string position
  • \+ - a literal +
  • 63 - a 63 substring.

See the regex demo and a PHP demo.

Please also consider Tpojka's suggestion to use a combination of intl-tel-input on front-end and libphonenumber-for-php on back-end if you need to sanitize and validate international phone numbers.



Answered By - Wiktor Stribiżew
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how can i append utm_source and utm_medium in all url from blog content

 November 20, 2022     laravel, php, preg-replace, preg-replace-callback     No comments   

Issue

Assume I have the below text in the database.

$str = 'Test text http://hello-world.com Test text  http://google.com/file.jpg?google=1 Test text https://hell.o.wor.ld/test?qwe=qwe Test text text text http://test.test/test hello all how are you I hope you all are fine ';

Now for this text, I want to add below utm_source and medium for all URL.

$utmUrl = "utm_source=source&utm_medium=email&utm_campaign=mycamp";

I already know that I can find all URL and do str_replace() but I want to do it with

preg_replace()

let me know if anyone knows any other solution

here the problem is some URL already have ? mark in URL so there I need to apped URL with & and where there is no ? there I need to append with ?


Solution

Edit Suggested by joy

Something like this.

$re ='/(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[-A-Z0-9+&@#\/%=~_|$?!:,.])*(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[A-Z0-9+&@#\/%=~_|$])/im';
$str = 'Test text http://hello-world.com Test text  http://google.com/file.jpg?google=1 Test text https://hell.o.wor.ld/test?qwe=qwe Test text text text http://test.test/test hello all how are you I hope you all are fine ';
$utmUrl = "utm_source=source&utm_medium=email&utm_campaign=mycamp";
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
foreach ($matches as $match)
    $str = preg_replace('%' . $match[0] . '%', $match[0] . (strpos($match[0], '?') !== false ? '&' : '?') . $utmUrl, $str);
var_dump($str);

Working Example

Edit: With preg_replace_callback

$re = '/(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[-A-Z0-9+&@#\/%=~_|$?!:,.])*(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[A-Z0-9+&@#\/%=~_|$])/im';
$str = 'Test text http://hello-world.com Test text  http://google.com/file.jpg?google=1 Test text https://hell.o.wor.ld/test?qwe=qwe Test text text text http://test.test/test hello all how are you I hope you all are fine ';
$utmUrl = "utm_source=source&utm_medium=email&utm_campaign=mycamp";
$str = preg_replace_callback($re, function ($match) use ($utmUrl) {
    return $match[0] . (strpos($match[0], '?') !== false ? '&' : '?') . $utmUrl . ' ';
}, $str);

var_dump($str);

Working Example

Old Answer.

Something like this.

$re = '%(https?://.*)\s%mU';
$str = 'Test text http://hello-world.com Test text  http://google.com/file.jpg?google=1 Test text https://hell.o.wor.ld/test?qwe=qwe Test text text text http://test.test/test hello all how are you I hope you all are fine ';
$utmUrl = "utm_source=source&utm_medium=email&utm_campaign=mycamp";
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
foreach ($matches as $match)
    $str = preg_replace('%' . $match[1] . '%', $match[1] . (strpos($match[1], '?') !== false ? '&' : '?') . $utmUrl, $str);
var_dump($str);

Working Example

Edit: With preg_replace_callback

$re = '%(https?://.*)\s%mU';
$str = 'Test text http://hello-world.com Test text  http://google.com/file.jpg?google=1 Test text https://hell.o.wor.ld/test?qwe=qwe Test text text text http://test.test/test hello all how are you I hope you all are fine ';
$utmUrl = "utm_source=source&utm_medium=email&utm_campaign=mycamp";
$str = preg_replace_callback($re, function ($match) use ($utmUrl) {
    return $match[1] . (strpos($match[1], '?') !== false ? '&' : '?') . $utmUrl . ' ';
}, $str);

var_dump($str);

Working Example



Answered By - Umair Khan
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, November 18, 2022

[FIXED] How to get last page url in twilio pagination php

 November 18, 2022     laravel, php, twilio, twilio-php     No comments   

Issue

$page = isset($input['page'])?$input['page']:0;
$perPageRecord = 10;
$calls = $this->twilio->calls->page(["to" => "+919876543210"],$perPageRecord,'',$page);
$data = [];
echo $calls->getNextPageUrl; 
exit;

I am using above code to get next page url and it print successfully. But i want to print last page url while In php twilio. Anyone can tell me how can i get last page url using twilio php. Thanks


Solution

It looks like you will need to programmatically extract a returned range and manipulate the resulting data to get the X most recent results (last page).

Replacing Absolute Paging and Related Properties

Usage and Migration Guide for Twilio's PHP Helper Library 5.x



Answered By - Alan
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Where is the Twiml xml for my application stored?

 November 18, 2022     laravel, twilio, twilio-api, twilio-php, twilio-twiml     No comments   

Issue

I have inherited a call center php application using twillio webrtc, and the twilio api.The trouble I'm having is the application, only makes a call to one number. I've looked through the controller using Twiml and Voice Response, and as far as I can tell a phone number gets passed from the front-end and $to_number is assigned that value.I've changed this value a million times , and it still dials the same number. It's because of this that I think that in my actual Twiml, is where it may be reset. The trouble is I can't find any Twiml in the entire application. I've also checked on twilio for any Twiml in my apps, and this is all I found. Twiml app When I try making a call using the call button, and an error is thrown.

I've been succesful in making calls to different numbers using the following request post request

In short, where is my Twiml (in xml) stored? Any ideas what may be causing this issue?


Solution

The TwiML Application SID is passed in the Access Token to the client. The TwiML Application has set of URL's, one being the Voice URL, that points to TwiML which tells Twilio what to do.

If the Access Token is being sent to the console log, you can decode it to find the Application SID (to lookup in Twilio Console) here. You can enable client side debug here.



Answered By - Alan
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, November 16, 2022

[FIXED] How to get Current page Title of Relationship Model in Laravel?

 November 16, 2022     eloquent, laravel, laravel-6, laravel-6.2     No comments   

Issue

i have some fields in my database table, and i want to display title,description and keywords according to every page, Please let me know how i can display this. My database fields name are metatitle,metadesc,keyword

Here are my Controller code where i am displaying the property list...

    public function listtype($slug){
    $prtype= Listing::whereHas('proType',function($q) use($slug){
        $q->where('slug','like','%'.$slug.'%');
    })->paginate(50);
    return view('property-type',compact('prtype','title'));
}

Solution

You can do the following way:

 public function listtype($slug){
    $prtype= Listing::whereHas('proType',function($q) use($slug){
        $q->where('slug','like','%'.$slug.'%');
    })->with('proType')->paginate(50);
    dd($prtype); /** for checking **/ 
    return view('property-type',compact('prtype', $prtype));
 }


Answered By - Amit Senjaliya
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I store avatar(image file) through Auth/RegisterController while user registration?

 November 16, 2022     laravel, laravel-6, php     No comments   

Issue

My intention is to store a profile pic with user registration. I am using Laravel 6 User Authentication. I tried to do it in given method.

My html code is like this..

<form method="POST" action="{{ route('register') }}" enctype="multipart/form-data">
    @csrf
    <input type="text" name="name" placeholder="Name"><br>
        @error('name')
            <div>{{$message}}</div>
        @enderror
    <input type="file" name="avatar" placeholder="Profile photo"><br>
        @error('avatar')
            <div>{{$message}}</div><br>
    @enderror
</form>

I added validation in Auth/RegisterController.validator(). I added fields to store data to create function. RegisterController class is given below..

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'avatar' => ['mimes:jpeg,jpg,png,gif','required','max:10000']
        ]);
    }
    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'avatar' => file($data['avatar'])->store('avatars')
        ]);
    }
}

When I try to run this code, this error will occur

Error
Call to a member function store() on array
http://localhost:8000/register 

Note: I removed email, password and other fields just to reduce number of lines..


Solution

You can upload avatar with laravel default registration by doing following steps.

1) Add avatar field in your migration

$table->string('avatar');

2) Add avatar field in $filable in User model

protected $fillable = [
    'name', 'email', 'password', 'avatar',
];

3) Add avatar input field in register.blade.php

<div class="form-group row">
    <label for="avatar" class="col-md-4 col-form-label text-md-right">{{ __('Avatar') }}</label>

    <div class="col-md-6">
        <input id="avatar" type="file" class="form-control @error('avatar') is-invalid @enderror" name="avatar" value="{{ old('avatar') }}" required autocomplete="avatar" autofocus>

        @error('avatar')
            <span class="invalid-feedback" role="alert">
                <strong>{{ $message }}</strong>
            </span>
        @enderror
    </div>
</div>

4) Add avatar in the validator function for validation

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => ['required', 'string', 'max:255'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:6', 'confirmed'],
        'avatar' => ['required', 'image'],
    ]);
}

5) Handle file upload in create function

protected function create(array $data)
{
    $request = app('request');
    if ($request->hasfile('avatar')) {
        $avatar = $request->file('avatar');
        $filename = time() . '.' . $avatar->getClientOriginalExtension();

        //Implement check here to create directory if not exist already 

        Image::make($avatar)->resize(300, 300)->save(public_path('uploads/avatars/' . $filename));
    }

    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'avatar' => !empty($filename) ? $filename : 'default_avatar.png',
    ]);
}

6) Before you try to Run this make sure you have Image Class available in your controller, If you don't have image class you can include it in your project by doing following steps.

composer require intervention/image

Now open the config/app.php file. Add this to the $providers array.

Intervention\Image\ImageServiceProvider::class

Next add this to the $aliases array.

'Image' => Intervention\Image\Facades\Image::class

Now include Image class in User Controller like this

use Image;

Try to run your project, it should work fine.



Answered By - Umer Abbas
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why are requests throttled for more time than specified in the middleware?

 November 16, 2022     laravel, laravel-6.2, php     No comments   

Issue

I have my routes declared like this:

Route::group(['prefix' => 'media', 'middleware' => 'auth'], function() {
    Route::group(['middleware' => 'throttle:120,1'], function() {
        Route::get('/', 'MediaController@index'); // <-- Route in question
        Route::delete('/{id}', 'MediaController@delete');
        Route::patch('/{id}', 'MediaController@edit');
    });
    Route::post('/', 'MediaController@upload')->middleware('throttle:100,1440');
});

If I understand the throttling middleware correctly, when user hits the rate limiting (120 requests in 1 minute) he should be throttled for the remaining time of the 1 minute period and then unblocked.

However, the blocking time is higher than 1 minute. See retry-after header: Returned retry-after header value is 180

(When I first noticed it, it was more than 600 seconds so it's not always 180 seconds)

Any ideas why would it be higher than 1 minute?


Solution

I figured it out!

Turns out the default behavior for the throttle middleware doesn't work per route. It just throttles requests per logged in user. And as you can see I had one route (the upload one) that has throttle:100,1440, and this caused problems resulting in much longer "punishments" even for routes with throttle:120,1.

My solution: I wrote my own version of the ThrottleRequests.php middleware that works per route:

  1. Place this file in your app/Http/Middleware folder.
  2. In app/Http/Kernel.php change your throttle route middleware to the new one:
'throttle' => \App\Http\Middleware\ThrottleRequestsPerRoute::class,
  1. Now whenever you assign a throttle middleware it will work per route.

Another solution: You can also use the default middleware and make use of the 3rd parameter. You can pass a prefix parameter like that: throttle:100,1440,upload. It will assign the upload prefix to the throttling key and rate limit the requests based on that. However, to achieve per route rate limiting you would have to assign a different prefix for each route.



Answered By - lukaszmtw
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to Count Value According to date in Laravel?

 November 16, 2022     eloquent, laravel, laravel-6, laravel-6.2, mysql     No comments   

Issue

I have multiple fields store in my database table, and there are followup field in my database and there are multiple dates store in this field. Now i want count data according to current date. But i am unable to do it.

I am getting same data multiple times, but i want in this format (Suppose there are 5 date store according to today date and they should be count 5, so that i can get the today followup clients )

Please let me know how i can do it.

Here are my controller code..

public function index()
 {
$lead=Lead::orderBy('created_at', 'desc')->get()
return view('admin.lead.index',compact('lead'));
 }

and here are my view file..

<div class="panel-heading">
@php
$mytime = Carbon\Carbon::now();
$checkdate=$mytime->toDateTimeString();
@endphp
<div class="panel-title">Today Follow Up's: 
    @foreach($lead as $lws)
        <span class="label label-warning">
            {{($lws->followup=$checkdate)}}
        </span>
    @endforeach
</div>
</div>

Solution

You can use below code to get only today's follow ups:

$lead=Lead::whereDate('followup', date('Y-m-d'))->get();

or to count the records:

$lead=Lead::whereDate('followup', date('Y-m-d'))->get()->count();


Answered By - Sehdev
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how can i fix this eror in laravel" 1005 Can't create table `englishcollage`.`role_user` (errno: 150 "Foreign key constraint is incorrectly formed"

 November 16, 2022     laravel, laravel-6, mysql, php     No comments   

Issue

i want to make a ACl migration in my Laravel project ... (version 6)

but i receive this annoying error :

General error: 1005 Can't create table English Collage.role_user (Errno: 150 "Foreign key constraint is incorrectly formed")")

English Collage is my database .

 Schema::create('permissions', function (Blueprint $table) {

          $table->increments('id');
          $table->string('title_fa'); // edit posts
          $table->string('title_en'); //edit-posts
          $table->timestamps();
      });


    Schema::create('roles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title_fa'); // edit posts
        $table->string('title_en'); //edit-posts
        $table->timestamps();
    });

    Schema::create('role_user', function (Blueprint $table) {

            $table->Integer('role_id')->unsigned();

        $table->Integer('user_id')->unsigned();


            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade')->onUpdate('cascade');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');

    });

    Schema::create('permission_role', function (Blueprint $table) {

        $table->unsignedInteger('permission_id');

        $table->unsignedInteger('role_id');


        $table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade')->onUpdate('cascade');
        $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade')->onUpdate('cascade');

    });

and this is my users migration:

 Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('image')->nullable();
            $table->string('level')->nullable();
            $table->integer('age')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });

this structure work in laravel 5 but laravel 6 has issue with this

i tried big integer and unsigned big integer even i tested primary_key for role_user


Solution

To create Foreign key the data type for the child column must match the parent column exactly.

Since id is a bigIncrements i.e. unsigned big integer in users table then role_user.user_id must be unsignedbigInteger, not an unsignedInteger.

Change below in your role_user table

 $table->Integer('user_id')->unsigned();

to

 $table->unsignedBigInteger('user_id');


Answered By - Sehdev
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to set the route in <a> tag with user id in Laravel 6?

 November 16, 2022     laravel, laravel-6, laravel-blade     No comments   

Issue

This is My index blade where I want to click on the user name and it will redirect me on the edit user blade

@extends('layouts.admin')

        @section('content')
          <h1><b>Users</b></h1>
          <table class="table table-hover">
              <thead>
              <tr>
                  <th scope="col">#</th>
                  <th scope="col">Profile</th>
                  <th scope="col">Name</th>
              </tr>
              </thead>
              <tbody>
              @if($users)
                  @foreach($users as $user)
              <tr>
                  <td>{{$user->id}}</td>
                  <td><img height="25" src="{{$user->photo ? $user->photo->file:'No photo exist'}}"></td>


                <!-- Problem is here -->
                  <td><a href="{{route('admin.users.edit', $user->id)}}" style="text-decoration: none"> 
                {{$user->name}}</a></td>


*it through an exception* 

**Route [admin.users.edit] not defined**       
              </tr>
                  @endforeach
                  @endif
              </tbody>
          </table>
        @endsection

If I use the url() method {{url('admin/users/edit',$user->id)}} like this it will redirect me as admin/users/edit/1 but my route is set as admin/users/1/edit. How can I open this route?


Solution

I will not suggest to use admin/users/1/edit even then if you want to use this then

Change

{{url('admin/users/edit',$user->id)}}

to

{{url('admin/users/'.$user->id.'/edit')}}

Reference:

Laravel ->URL Generation -> Generating Basic Url



Answered By - Sehdev
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] When trying to insert data got this error msg Add [name] to fillable property to allow mass assignment on [App\Suitspecialist]

 November 16, 2022     get, laravel, laravel-6, post     No comments   

Issue

Can anyone explain it to me why controller portion throwing error?

Here is my MODEL:

class Suitspecialist extends Authenticatable
{
    use Notifiable;
    protected $guard = 'suitspecialist';
    protected $fillable = [
        'name', 'email', 'password',
    ];
    protected $hidden = [
        'password', 'remember_token',
    ];
}

CONTROLLER

This portion throws an error

Add [name] to fillable property to allow mass assignment on [App\Suitspecialist].

protected function createSuitspecialist(Request $request)
{
    $this->validator($request->all())->validate();
    Suitspecialist::create([
        'name' => $request->name,
        'email' => $request->email,
        'password' => Hash::make($request->password),
    ]);
    return redirect()->intended('login/suitspecialist');
}

Solution

When you try to fill severeal properties on a model using a method like fill, create or update, you need to specify the fields that can be filled this way. This is call "mass assignment".

This is an Eloquent security implemented to avoid that you store data you don't want to.

In your model, use the guarded or fillable attributes to specify which properties you want or don't want to register use mass assignment. These properties accepts an array.

Look in the Laravel documentation it is well explained : https://laravel.com/docs/7.x/eloquent#mass-assignment



Answered By - Benjamin Masi
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to create a template view table tag without repeating table tags on every file

 November 16, 2022     laravel, laravel-6, laravel-7, laravel-views     No comments   

Issue

I'm developing a system which has many tables so I have to repeat the writing of table tags on all the files which display a table Here is what I'm doing on every file which have to display table

On Countries table:

  <table class="table table-striped table-hover table-sm" id="table">
                        <thead class="text-uppercase text-center bg-primary">
                        <tr class="text-white">
                            <th scope="col">Name</th>
                            <th scope="col">Slug</th>
                            <th scope="col">Population</th>
                            <th scope="col">Region</th>
                            <th scope="col">Cities</th>
                            <th scope="col">Descriptions</th>
                            <th scope="col" >Actions</th>
                        </tr>
                        {{ csrf_field() }}
                        </thead>
                        <tbody>
                            @foreach ($countries as $country)
                                <tr>
                                    <td class="text-left">{{$country->name}}</td>
                                    <td class="text-center">{{$country->slug}}</td>
                                    <td class="text-right">{{$country->population}}</td>
                                    <td class="text-center">{{$country->region->name}}</td>
                                    <td class="text-center">{{$country->city_count}}</td>
                                    <td class="text-left">{{$country->desc}}</td>
                                    <td class="text-center">
                                        <div class="btn-group">

                                            @can('country-update')
                                                <a class="btn btn-primary btn-sm mr-2" href="{{route('location.countries.edit',$country)}}" title="Edit"><i class="fa fa-edit"></i></a>
                                            @endcan

                                            @can('country-delete')
                                                <form class="form-delete" method="post" action="{{route('location.countries.destroy',$country)}}">
                                                    @method('DELETE')
                                                    @csrf
                                                    <button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure?')"><i class="fa fa-trash-alt"></i></button>
                                                </form>
                                            @endcan
                                        </div>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>

then on the cities I'll do the same but with different table head names and table data

 <table class="table table-striped table-hover table-sm" id="table">
                    <thead class="text-uppercase text-center bg-primary">
                    <tr class="text-white">
                        <th scope="col">Name</th>
                        <th scope="col">Slug</th>
                        <th scope="col">Country</th>
                        <th scope="col">Descriptions</th>
                        <th scope="col" >Actions</th>
                    </tr>
                    {{ csrf_field() }}
                    </thead>
                    <tbody>
                        @foreach ($cities as $city)
                            <tr>
                                <td class="text-left">{{$city->name}}</td>
                                <td>{{$city->slug}}</td>
                                <td class="text-center">{{$city->country->name}}</td>
                                <td class="text-left">{{$city->desc}}</td>
                                <td class="text-center">
                                    <div class="btn-group">

                                        @can('city-update')
                                            <a class="btn btn-primary btn-sm mr-3" href="{{route('location.cities.edit',$city)}}" title="Edit"><i class="fa fa-edit"></i></a>
                                        @endcan

                                        @can('city-delete')
                                            <form class="form-delete" method="post" action="{{route('location.cities.destroy',$city)}}">
                                                @method('DELETE')
                                                @csrf
                                                <button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure?')" title="delete"><i class="fa fa-trash-alt"></i></button>
                                            </form>
                                        @endcan
                                    </div>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table> 

but I wat to have a template where I'll only populate table head rows and table body something like this

<div class="table-responsive">
    <table class="table table-striped table-hover table-sm" id="table">
        <thead class="text-uppercase text-center">
        <tr>
            //Dynamic table heads
            @if(!is_null($rows))
                @foreach($rows as $row)
                    {{$row}}
                @endforeach
            @endif
        </tr>
        </thead>
        <body>
            //Dynamic table body
            @if(!is_null($datas))
                @foreach($datas as $data)
                    {{$data}}
                @endforeach
            @endif
        </tbody>
    </table>
    <!-- end table -->
</div>

What is the best way to accomplish this


Solution

You can use Blade component for that. One of approaches in Laravel 7 is to use Blade class component. Link to official Blade components docs: https://laravel.com/docs/7.x/blade#components

You can create a generic table component using artisan command:

php artisan make:component Table

Component class

Your component could look like that:

<?php 

namespace App\View\Components;

use Illuminate\View\Component;

class Table extends Component
{
    /**
     * Array of table heading strings
     *
     * @var array
     */
    public $headings;

    /**
     * Table rows
     *
     * @var array
     */
    public $rows;

    /**
     * Create the component instance.
     *
     * @param  string  $type
     * @param  string  $message
     * @return void
     */
    public function __construct($headings, $rows)
    {
        $this->headings = $headings;
        $this->rows = $rows;
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\View\View|string
     */
    public function render()
    {
        return view('components.table');
    }
}

Component view

Now when you have component class, you have to prepare the component view. You will found it in /resources/views/components/table.blade.php.

<div class="table-responsive">
    <table class="table table-striped table-hover table-sm" id="table">

        //Dynamic table heads
        @if($headings)
        <thead class="text-uppercase text-center">
            <tr>
                @if($rows))
                    @foreach($rows as $row)
                        <th>{{$row}}</th>
                    @endforeach
                @endif
            </tr>
        </thead>
        @endif

        <tbody>
            //Dynamic table body
            @foreach($rows as $row)
                <tr>
                    // Render each item from row
                    @foreach($row as $item)
                        <td>{{$item}}</td>
                    @endforeach
                </tr>
            @endif
        </tbody>
    </table>
    <!-- end table -->
</div>

Now you can use your component in your views:

<x-table :headings="['foo', 'bar']" 
         :data="[['foo1', 'bar1'], ['foo2', 'bar2']]" class="mt-4"/>


Answered By - Michael DojĨár
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to stop GET on a POST route (laravel)

 November 16, 2022     laravel, laravel-6, laravel-7     No comments   

Issue

I'm new to laraval. I got this POST route but if someone try the address on the browser it become a GET route and laravel throw a error. Is there a way to throw a 404 page for a GET request on POST route.

Route::post('/step2Validate', 'StepController@step2Validate');

If this route is access as GET "The GET method is not supported for this route. Supported methods: POST." error is given.


Solution

Try this:

Route::get('/step2Validate', function() { 
    abort(404); 
    }
);


Answered By - Dimitri Mostrey
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing