What is the best way to learn programming and its frameworks? [closed]

Well, I’ve been learning PHP and I’m still finding the best way to get used to it as I’m still a beginner. So, if anyone has proper means I can use I’d love to know because I really need a proper advice as I don’t like being in a mix.
Also, I’m learning how to use PHP frameworks and I’ve begun with Laravel and I’m finding a hard time getting a proper learning source since its documentation is really providing information the halfway or maybe the problem is me. So, I will also appreciate suggestions for a proper tutorial.

I tried going through documentation from official Laravel website and it’s a bit confusing.

Laravel factory startup error Array to string conversion

In my Laravel project I am using the Astrotomic Laravel Translatable package. I want to create a factory to generate random data.My factory code

public function definition(): array
{
    $locales = ['uk', 'ru'];

    $translations = collect($locales)->mapWithKeys(function($locale) {
        return [
            $locale => [
                'slug' => fake()->unique()->randomNumber(4) . '-' . fake()->slug(3),
                'name' => fake()->unique()->name(),
                'description' => fake()->text(),
                'education' => fake()->text(),
            ]
        ];
    })->toArray();

    return array_merge([
        'city_id' => City::get()->random()->id,
        'degree' => fake()->numberBetween(1, 2),
        'qualification' => fake()->numberBetween(1, 3),
        'start_year' => fake()->year(),
        'viewed' => fake()->numberBetween(50, 5500),
        'status' => true,
        'image' => fake()->imageUrl(250, 250),
        'sort_order' => fake()->numberBetween(0, 10),
        'created_at' => fake()->dateTimeBetween('-4 week', '-3 week'),
        'updated_at' => fake()->dateTimeBetween('-2 week', '-1 week'),
    ], $translations);
}

I get an error when starting the factory, please help me(

   ErrorException

  Array to string conversion

  at vendorlaravelframeworksrcIlluminateSupportStr.php:964
    960▕
    961▕         $result = array_shift($segments);
    962▕
    963▕         foreach ($segments as $segment) {
  ➜ 964▕             $result .= (array_shift($replace) ?? $search).$segment;
    965▕         }
    966▕
    967▕         return $result;
    968▕     }

  1   vendorlaravelframeworksrcIlluminateSupportStr.php:964
      IlluminateFoundationBootstrapHandleExceptions::IlluminateFoundationBootstrap{closure}()

  2   vendorlaravelframeworksrcIlluminateDatabaseQueryException.php:67
      IlluminateSupportStr::replaceArray()

how to pass third array into loop to append the value to td

<?php
                                $siteFloorData = [];
                                $siteTitleData = [];
                                foreach($siteStages as $data)
                                {
                                    array_push($siteFloorData , $data->NoofFloor);
                                }
                                foreach($siteStages as $data)
                                {
                                    array_push($siteTitleData , $data->StagesName);
                                }
                                $floorType= ['Stilt','1st','2st','3rd','4th','5th'];
                            ?>
                            <div class="row">
                                <table class="table table-bordered" >
                                    <thead>
                                    <tr>
                                        <th scope="col" colspan="6" class="">STAGE OF CONSTRUCTION</th>
                                      
                                    </tr>
                                    </thead>
                                    <tbody>
                                            <?php for ($i = 0; $i < count($siteTitleData); $i++) {
                                                $name = $siteTitleData[$i];
                                                $inputCount = $siteFloorData[$i];
                                                
                                                ?>
                                            <tr>
                                            <th scope="row" >{{ $name }}</th>
                                            <?php for ($j = 1; $j <= $inputCount; $j++) { ?>
                                                <?php
                                                
                                                if($i == 1)
                                                {
                                                    $flrType = $floorType[$i];
                                                    ?>
                                                    <td class="site-bg">{{ $floorType }}</i></td>
                                                    <?php
                                                }
                                                ?>
                                           
                                            <?php } ?>
                                            </tr>
                                            <?php
                                            }
                                           ?>
                                    </tbody>
                                </table>

have three array’s . First one are all Title and second on are all no of td need to show.

everything fine till scenario where for second title need to show list of topics, so i created static array as third one. but i can’t able to get the result. 1st value only repeating in all td.

Output :

enter image description here

Cron Job runs multiple times in Laravel – Production Server

I have a project in Laravel 8 as the backend deployed on EC2 with ubuntu. I have scheduled few functions as cron jobs at specific time. But, the same cron job seems to run multiple times. So i put a test function as follows.

     $schedule->call(function () {
        Log::info('function testing');
     })->dailyAt('8:00')->timezone('Asia/Qatar');

The above log prints around 39 times. After my research i added withoutOverlapping()

     $schedule->call(function () {
        Log::info('function testing');
     })->dailyAt('8:00')
       ->timezone('Asia/Qatar')
       ->name('unique_event_name')
       ->withoutOverlapping();

The above one prints around 9 times.

I have a development server with the same code and similiar env. There it works fine. It is running only one time.

* * * * * cd backend_path && php artisan schedule:run >> /dev/null 2>&1

The above command i runs on crontab -e.

I’m unable to figure out the issue with my production server, Any help will be appreciated !!

Laravel sessions – can a session variable disappear, while a user stays logged in?

First off, I do know that there’s other threads about session variables disappearing. I’ve seen this one, for example. My question isn’t just, can session variables disappear.

My question is about the relationship between a session variable, and a user’s log-in session. In Laravel, I can get the current user by Auth::user().

Is it possible that, at minute 1 of a users login session, I set a session variable, like session(['x' => Auth::user()->id]) for example, and then at say minute 61, that user is still logged in, so Auth::user() is still returning the correct user, but now when I call session('x') that session variable has become unset?

Is the users login desynced from the session() variables? I thought a user was logged in through the session in the first place. But I’m getting situations where a user is still logged in, but some of my other custom session variables are disappearing, that’s the context for this question. It has me very confused.

Is there a way to override core Moodle forms to add more fields? like category form

I’m trying to figure a way to add more fields to the category form in Moodle, is there a way to achieve that through local plugins? I have tried making a local plugin with the same file structure for editcategory_form.php and made a custom one with the same original file in addition to the new fields, the plugin gets recognized and installed and has it’s own settings page that I can access but Moodle keeps serving me the original editcategory_form.php, how can I override it so it serves my copy of the form instead?

Class “does not comply with psr-4 autoloading standard.” when trying to develop a composer package in Laravel

Trying to develop a package locally within a Laravel application. In my root laravel application I have a packages directory, structure below

packages
└── deco-network-api
    ├── composer.json
    ├── src
    │   └── BananaMoonClothing
    │       └── DecoNetworkApiClient
    │           ├── DecoNetworkApiClient.php
    │           └── DecoNetworkApiServiceProvider.php
    └── vendor
        ├── autoload.php
        └── composer
            ├── ClassLoader.php
            ├── LICENSE
            ├── autoload_classmap.php
            ├── autoload_namespaces.php
            ├── autoload_psr4.php
            ├── autoload_real.php
            ├── autoload_static.php
            └── platform_check.php

7 directories, 12 files

composer.json of the package

{
    "name": "banana-moon-clothing/deco-network-api",
    ...
    "autoload": {
        "psr-4": {
            "BananaMoonClothing\DecoNetworkApiClient\": "src/"
        }
    },
    "extra": {
        "laravel": {
            "providers": [
                "BananaMoonClothing\DecoNetworkApiClient\DecoNetworkApiServiceProvider"
            ]
        }
    },
    ...
}

Snippet from packages/deco-network-api/src/BananaMoonClothing/DecoNetworkApiClient/DecoNetworkApiClient.php

<?php

namespace BananaMoonClothingDecoNetworkApiClient;

...

class DecoNetworkApiClient
{
    ...
}

Snippet from packages/deco-network-api/src/BananaMoonClothing/DecoNetworkApiClient/DecoNetworkApiServiceProvider.php

<?php

namespace BananaMoonClothingDecoNetworkApiClient;

...

class DecoNetworkApiServiceProvider extends ServiceProvider
{
   ...
}

I’m requiring the package in my laravel Application, as below

{
    "name": "laravel/laravel",
    ...
    "require": {
        ...
        "banana-moon-clothing/deco-network-api": "^1.0.0"
    },
    ...
    "repositories": [
        {
            "type": "path",
            "url": "./packages/deco-network-api"
        }
    ],
    ...
}

When ever I run composer update from the larave application I get the following

...
Class BananaMoonClothingDecoNetworkApiClientDecoNetworkApiServiceProvider located in ./vendor/banana-moon-clothing/deco-network-api/src/BananaMoonClothing/DecoNetworkApiClient/DecoNetworkApiServiceProvider.php does not comply with psr-4 autoloading standard. Skipping.
Class BananaMoonClothingDecoNetworkApiClientDecoNetworkApiClient located in ./vendor/banana-moon-clothing/deco-network-api/src/BananaMoonClothing/DecoNetworkApiClient/DecoNetworkApiClient.php does not comply with psr-4 autoloading standard. Skipping.
> IlluminateFoundationComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi

In ProviderRepository.php line 206:

  Class "BananaMoonClothingDecoNetworkApiClientDecoNetworkApiServiceProvider" not found


Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1

I can’t for the life of me see what the issue might be, I think I’ve just done something silly.

Memory leak in Event while broadcasting in Laravel 8.x

Whenever I try to call an event in Laravel 8, a memory leak happens and it crashes the server.
Here is the event:

class NewOrderEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $order_id;
    public $user_id;
    
    public function __construct($order_id, $user_id)
    {
        $this->order_id = $order_id;
        $this->user_id =  $user_id;
    }

    public function broadcastOn()
    {
        Log::info('Memory usage broadcastOn: '. memory_get_peak_usage());
        return [new Channel('orders-' . $this->user_id)];
    }

    public function broadcastWith()
    {
        Log::info('Memory usage broadcastWith: '. memory_get_peak_usage());
        
        return [
            'id' => $this->order_id,
        ];
    }

    public function broadcastAs()
    {
        return ('orders');
    }
}

And the logs:

local.INFO: Memory usage broadcastOn: 5787040  
local.INFO: Memory usage broadcastWith: 5787312  

How can I reduce the memory usage of the event?

I’ve tried to free $this->user_id but it didn’t work

ERROR:
Request Timeout
This request takes too long to process, it is timed out by the server. If it should not be timed out, please contact the administrator of this website to increase the ‘Connection Timeout’.

Symfony Bundle – values not updating when changing /packages/.yaml

I’m working on a Symfony bundle at the moment and have got it working apart from one issue which I am really struggling to figure out.

In my bundles Extension file I ensure entity_tables.yaml is created in the installing projects config/packages/ directory:

// entity-tables-bundle/src/DependencyInjection/EntityTablesExtension.php
public function load(array $configs, ContainerBuilder $container): void
{
    $configuration = new Configuration();
    $config = $this->processConfiguration($configuration, $configs);

    $yamlConfig = [
        'entity_tables' => $config,
    ];
    $yaml = Yaml::dump($yamlConfig, 4);

    $yamlFilePath = $container->getParameter('kernel.project_dir') . '/config/packages/entity_tables.yaml';

    file_put_contents($yamlFilePath, $yaml);

    $loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
    $loader->load('entity_tables.yaml');

    $this->modifyTwigConfiguration($container);
}

private function modifyTwigConfiguration(ContainerBuilder $container): void
{
    $twigConfigFile = $container->getParameter('kernel.project_dir') . '/config/packages/twig.yaml';
    $twigConfig = Yaml::parseFile($twigConfigFile);

    if (!isset($twigConfig['twig']['paths']['%kernel.project_dir%/vendor/dannyxcii/entity-tables-bundle/src/Resources/views'])) {
        $twigConfig['twig']['paths']['%kernel.project_dir%/vendor/dannyxcii/entity-tables-bundle/src/Resources/views'] = 'EntityTables';
    }

    if (!isset($twigConfig['twig']['globals']['entity_tables_currency'])) {
        $twigConfig['twig']['globals']['entity_tables_currency'] = '%entity_tables.currency%';
    }

    $dumper = new Dumper();
    $yaml = $dumper->dump($twigConfig, 4);

    file_put_contents($twigConfigFile, $yaml);
}

The modifyTwigConfiguration method adds a global and the namespace for the twig templates which wasn’t getting done automatically as the Symfony docs state. My Configuration is very simple:

// entity-tables-bundle/src/DependencyInjection/Configuration.php
public function getConfigTreeBuilder(): TreeBuilder
{
    $treeBuilder = new TreeBuilder('entity_tables');

    $treeBuilder->getRootNode()
        ->children()
            ->scalarNode('currency')
            ->defaultValue('£')
            ->end()
        ->end();

    return $treeBuilder;
}

And the contents of my packages entity_tables.yaml:

parameters:
  entity_tables.currency: '£'

Which adds this config to my app:

entity_tables:
  currency: £

So now when my bundle is installed via Composer, the bundle is added automatically to config/bundles.php and my YAML file is created as shown above. I can access this in my controllers with $this->getParameter('entity_tables.currency') and in my templates with entity_tables_currency.

Question: When I update the value in config/packages/entity_tables.yaml (to $), the value is not updated when accessing – £ is still displayed. Does anyone know why?

What I tried: I have tried:

  • bin/console cache:clear --env=prod + bin/console cache:clear --env=dev
  • Ran php bin/console debug:container --parameters and the param still displays the original/default value
  • Restarted Docker containers and cleared browser cache

I am using Symfony 6.2.

ODBC Driver 18 for SQL Server doesn’t allow PHP PDO to connect

I’m in the process of updating our pipeline due to upgrading the required PHP version. In the process I needed to change our MSSQL client to sqlcmd and I installed msodbcsql18 mssql-tools18 unixodbc-dev. With this change the SQL driver now requires a valid cert for the SQL to allow connection. With sqlcmd I just needed to add a flag to bypass this, but our automated tests against the MSSQL database aren’t allowed to connect with error:

SQLSTATE[08001]: [Microsoft][ODBC Driver 18 for SQL Server]SSL Provider: [error:0A000086:SSL routines::certificate verify failed:self-signed certificate]

I’ve being able to find the same issue for Laravel, but none that would be using PDO for the connection. I’ve tried passing the following options array to try to add the parameters to the connection that would allow it to ignore the cert validity but no success

[
    'trust_server_certificate' => true, // 'TrustServerCertificate' too
    'encrypt' => 'no', // 'Encrypt' => 'yes' as well
]

Any solutions for this?

Call to an undefined method with personaliced builder phpstan

I´m working with laravel and i have installed larastan and when execute this library, return me this message:

Call to an undefined method
         AppBuildersLiquidBuilder::conTipoGrupo().

This method it´s in my personaliced builder and his body it´s:

public function conTipoGrupo(): self
    {
        return $this->leftJoin
...

i´m calling this method in other function and i´m building a query

$regs = GrupoLiquidaciones::conAplicaciones()
            ->conTipoGrupo()

In my model i´m instancing to my builder and i have my phpDoc because it´s personaliced builder:

/**
     * @param Builder $query
     * @return BuilderGrupoLiquidaciones
     * 
     * Devuelve una instancia del Builder de grupos de liquidacion
     */
    public function newEloquentBuilder($query): LiquidBuilder
    {
        return new BuilderGrupoLiquidaciones($query, $this->table);
    }

i don´t know that i should to do to solve this message. Thanks for readme and sorry for my bad english

Keep old value checkbox laravel

I have a Laravel 9.x project, and when I submit the form and an error occurs, I have managed to keep the already inserted value of the text fields, but I would like the checkboxes to keep their value as well.

<input type="checkbox" name="abono_tasa" value="{{ isset($vado->abono_tasa) ? ($vado->abono_tasa==1 ? 'checked': '') : '' }}" id="abono_tasa">

I would like to control this.

Can we redirect to another route with condition in destroy() in laravel?

Scenario: A post has a delete button in all posts list view and the postShow view. So if the post is deleted from the list it will return back()->with(‘success’, ‘Some message’) but if we delete it from the postShow view then redirect to the home.

(in short if the the post is deleted via show page then it redirects to home else redirect back)

{
    $post = Post::findOrFail($id);
    $post->delete();

    if(route('post.show', $post->slug)){
        return redirect()->route('home')->with(["message" => "Your Post has been deleted successfully");
    } else {
        return back()->with(["message" => "Your Post has been deleted successfully");
    }
}

This is the code but it is always redirecting to home.

Generate multilevel WSDL multilevel using Laminas SOAP in laravel

i’m trying to figure how to generate multilevel wsdl using Laminas SOAP in my Laravel.. i did read the documentation and chatgpt too.. but im still confused how to set up, here’s the link :
https://docs.laminas.dev/laminas-soap/auto-discovery/

This is my controller code :

public function soap()
{
    $server = new Server(
        route('soap-wsdl'),
        [
            'actor' => route('soap-server'),
        ]
    );

    $this->populateServer($server);
    $server->setReturnResponse(true);

    $response = response($server->handle());
    $response->header('Content-Type', 'text/xml');

    return $response;
}

public function wsdl(Request $request)
{
    $wsdl = new AutoDiscover();

    $this->populateServer($wsdl);
    $wsdl->setUri(route('soap-server'))
        ->setServiceName('InaportWSDL');

    return response()->make($wsdl->toXml())
        ->header('Content-Type', 'application/xml');
}

private function populateServer($server)
{
    // Expose a class and its methods:
    $server->setClass(ResponseServices::class);
}

and this is my ResponseServices class (or Controller) :

class ResponseServices {
/**
 * @param string $user
 * @param string $password
 * @param array $detail
 * @return array
 */
public function entryRpkro($user, $password, $detail)
{
}

}

result using wizdler :

<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
<Body>
    <entryRpkro xmlns="http://localhost:8000/soap">
        <user>[string]</user>
        <password>[string]</password>
        <detail>[Array]</detail>
    </entryRpkro>
</Body>
</Envelope>

So i want to change this wsdl into this :

<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
<Body>
    <entryRpkro xmlns="http://localhost:8000/soap">
        <user>[string]</user>
        <password>[string]</password>
        <detail>
          <name>[string]</name>
          <age>[int]</age>
        </detail>
    </entryRpkro>
</Body>
</Envelope>

Woocommerce custom cart text based on product category

as the title suggests, I have to show a custom text in the woocommerce cart, based on the product category added by the customer

// Add a function to show custom text on the cart page
add_action( 'woocommerce_before_cart', 'show_custom_text' );

// Define the function
function show_custom_text() {
  // Get the current cart
  $cart = WC()->cart;
  
  // Check if the cart is empty
  if ( $cart->is_empty() ) {
    return;
  }
  
  // Create an associative array with the product categories and related texts to display
  $categories_and_texts = array(
    '1' => 'This is text 1',
    '2' => 'This is text 2',
    '3' => 'This is text 3',
    // Add more categories and lyrics here
  );
  
  // Create an empty array to store the categories in the cart
  $categories_in_cart = array();
  
  // Iterate over all the items in the cart
  foreach ( $cart->get_cart() as $cart_item ) {
    // Get the current product
    $product = $cart_item['data'];
    
    // Get product categories
    $product_categories = wp_get_post_terms( $product->get_id(), 'product_cat' );
    
    // Iterate over all product categories
    foreach ( $product_categories as $product_category ) {
      // Get the category slug
      $category_slug = $product_category->slug;
      
      // Check if the category is among those defined in the associative array
      if ( array_key_exists( $category_slug, $categories_and_texts ) ) {
        // Add the category to the array of categories in the cart, if not already present
        if ( ! in_array( $category_slug, $categories_in_cart ) ) {
          $categories_in_cart[] = $category_slug;
        }
      }
    }
  }
  
  // Check if there are any categories in the cart
  if ( ! empty( $categories_in_cart ) ) {
    // Show a message before custom texts
    echo '<p>Attention, you have added products from the following categories to your cart:</p>';
    
    // Iterate over all the categories in the cart
    foreach ( $categories_in_cart as $category ) {
      // Show the text corresponding to the category
      echo '<p>' . $categories_and_texts[$category] . '</p>';
    }
  }
}

I’m trying this function but it doesn’t seem to work

I’d like to show the text also in the thankyou page and in the order email

Thank you