Laravel project organization [closed]

I’m trying to learn to program with laravel! I would like to understand how to best organize a project.

The project I would like to develop is the following:

Create a web app for a roulette betting strategy.

the strategy is based on the fibonacci sequence (0 1 1 2 3 5 7 12 etc.) so each bet is the sum of the previous two.

but I want to bet on a “column” or “row” of the roulette table only when it hasn’t come out for at least 5 consecutive times.

therefore I have to create a form in which I insert the last number that came out and save it in a sequence of numbers.

from the sequence check how many times each column and row hasn’t come out.

when one of these is not drawn for 5 consecutive times, highlight it as “to bet” and assign the bet 1 of the Fibonacci sequence eg € 1.00

if it is not drawn in the subsequent rounds, increase the bet following the Fibonacci sequence until that column or row is drawn.

at this point the sequence must be reset and you start again from the beginning counting from how many extractions the columns and rows have not come out.

it should not be too complicated but I do not understand how I should manage the models and functions to calculate the columns, rows and the bets following the numbers drawn.

I hope someone can give me some advice.

Thanks

How can be used TagsInput component to store related data using model hasmany relationship?

I have eloquent model to store specific car brand model years:

<?php

namespace AppModels;

use IlluminateDatabaseEloquentBuilder;
use IlluminateDatabaseEloquentModel;

class CarModel extends Model
{
    protected $fillable = ['brand_id', 'name'];

    public function brand()
    {
        return $this->belongsTo(CarBrand::class, 'brand_id');
    }

    public function years()
    {
        return $this->hasMany(CarModelYear::class, 'model_id');
    }

    public function classifications()
    {
        return $this->hasMany(CarClassification::class, 'model_id');
    }

    public function scopeWithCarStats(Builder $query)
    {
        $query->withCount([
            'classifications as totalClassifications',
        ]);

        $carClasses = CarClass::pluck('id');
        foreach ($carClasses as $carClassId) {
            $query->withCount([
                "classifications as car_class_{$carClassId}" => function (Builder $query) use ($carClassId) {
                    $query->where('class_id', $carClassId);
                }
            ]);
        }

        $carYears = CarModelYear::query()
            ->select('year')
            ->distinct()
            ->orderBy('year', 'asc')
            ->pluck('year');

        if($carYears->isNotEmpty()) {
            foreach ($carYears as $year) {
                $query->selectRaw("
                    (SELECT COUNT(*)
                     FROM car_classifications
                     JOIN car_model_years ON car_classifications.year_id = car_model_years.id
                     WHERE car_classifications.model_id = car_models.id
                     AND car_model_years.year = ?) as car_model_year_{$year}
                ", [$year]);
            }
        }
    }
}

class CarModelYear extends Model
{
    protected $fillable = ['model_id', 'year'];

    public function model()
    {
        return $this->belongsTo(CarModel::class, 'model_id');
    }

    public function classifications()
    {
        return $this->hasMany(CarClassification::class, 'year_id');
    }

    public function scopeWithCarStats(Builder $query)
    {
        $query->withCount([
            'classifications as totalClassifications',
        ]);

        $carClasses = CarClass::pluck('id');
        foreach ($carClasses as $carClassId) {
            $query->withCount([
                "classifications as car_class_{$carClassId}" => function (Builder $query) use ($carClassId) {
                    $query->where('class_id', $carClassId);
                }
            ]);
        }
    }
}

Here is my CarModel resource form:

public static function form(Form $form): Form
{
    return $form
        ->schema([
            FormsComponentsSection::make()
                ->columns()
                ->schema([
                    FormsComponentsTextInput::make('name')
                        ->label('Model Name')
                        ->required()
                        ->maxLength(255),
                    FormsComponentsSelect::make('brand_id')
                        ->label('Car Brand')
                        ->relationship('brand', 'name')
                        ->searchable()
                        ->preload()
                        ->required(),
                    FormsComponentsTagsInput::make('years')
                        ->label('Model Years')
                        ->placeholder('Enter model years, example: 2020, 2021, 2022')
                        ->required()
                        ->dehydrated(false)
                        ->unique()
                        ->splitKeys([',', ' '])
                        ->hint('Eneter model years with comma or space'),
                ])
        ]);
}

I tried debugging in CreateCarModel method named mutateFormDataBeforeCreate but not triggered anything:

protected function mutateFormDataBeforeCreate(array $data): array
{
    if(array_key_exists('years', $data)) {
        dd($data['years']);
    }

    return $data;
}

I get error when try create some model with specific years:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'years' in 'where clause' (Connection: mysql, SQL: select count(*) as aggregate from `car_models` where `years` = 2024)

How I can correctly use TagsInput component to store car model years?

Warning: mysqli_stmt_bind_param(): Argument must be passed by reference, value given [duplicate]

I use the following code to prepare a statement for msqli:

if($verfahren != ""){
    $where[] = "FIND_IN_SET(?,`verfahren`)>0";
    $types[] = "s";
    $params[] = $verfahren;
}
if($fachgebiet != ""){
    $where[] = "FIND_IN_SET(?,`fachgebiet`)>0";
    $types[] = "s";
    $params[] = $fachgebiet;
}
if($praxis != ""){
    $where[] = "`praxis` = ?";
    $types[] = "s";
    $params[] = $praxis;
}

$sql = "SELECT * FROM `my_table`";
if(isset($where)){
    $sql .= " WHERE ". implode(' AND ', $where);
    $stmt = mysqli_prepare($mysqli, $sql);
    # https://stackoverflow.com/a/43216404/25634160
    $refs = [$stmt, implode('', $types)];
    foreach($params as $param){
        $refs[] = $param;
    }
    unset($param);
    call_user_func_array('mysqli_stmt_bind_param', $refs);  <= Warning
} else {
    $stmt = mysqli_prepare($mysqli, $sql);
}

The fourth to last line throws three warnings:

Warning: mysqli_stmt_bind_param(): Argument #3 must be passed by reference, value given in /path/to/script.php on line 254

Warning: mysqli_stmt_bind_param(): Argument #4 must be passed by reference, value given in /path/to/script.php on line 254

Warning: mysqli_stmt_bind_param(): Argument #5 must be passed by reference, value given in /path/to/script.php on line 254

I understand from other Q&A here, such as this one, that I need to pass my variables as variables instead of values. What I don’t understand is where in my code I need to do that and how.

Could you please explain to me how I need to change my code?

Photo gallery Page [closed]

I am creating a website for a gaming server. One of the pages on the site is a photo gallery. I’ve created the gallery layout in a page called PhotoGallery.php. There are 3 options. The 1st is a radio input choosing either Photo or Video. The 2nd is a drop down menu that gets populated through a php function. This function locates the directory names in either /Images/Photo_Gallery/Pictures/ or /Video/Video_Gallery/Video/and echo back the directory names and option tags for the drop down. This menu is also hidden until the radio menu choice is made. This is done in a javascript function. This choice is then passed back to php to get the sub directories of the chosen path. The 3rd option another drop down menu that takes the value of the radio and the 1st drop down menu is populated with the directory names of the category folder if any. Then once all choices are made the gallery then displays all the pictures or videos Thumbnails found in that folder.

I have worked on this for 2 weeks now and can’t seem to get it working properly to populate the menus. I get the menu to show up but no option inside of it. Is there something wrong with my syntax or logic or is there a better cleaner approach?

PhotoGallery.php // code <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Photo Gallery</title> <link rel="stylesheet" href="../../CSS/styles.css"> <link rel="stylesheet" href="../../CSS/photo_gallery.css"> <script src="../../Javascript/photo_gallery_functions.js"></script> </head> <header> <?php include "../../Website_Pages/Element_Pages/header.php" ?> </header> <body> <div class="photo_gallery_main_background_container"> <div class="left_nav_container"> <?php include "../../Website_Pages/Element_Pages/leftmenu.php" ?> </div> <div class="photo_gallery_main_container"> <h1>COMMUNE GALLERY</h1> <div class="background_container"> <div class="gallery_header" id="gallery_header"> <h2>"Collection"</h2> <div class="drop_down_menu_container" id="drop_down_menu_container"> <form action="../../PHP/photo_gallery_functions.php" method= "post"> <input type="radio" id="media_type_photo" name="media_type" value="Photo" checked="checked" onclick= showDropdown()> <label for="media_type_photo">Photo</label> <br> <input type="radio" id="media_type_video" name="media_type" value="Video" onclick= showDropdown()> <label for="media_type_video">Video</label> <br> <input type="submit" value="Submit"> </form> <br> <form action="../../PHP/photo_gallery_functions" method="get"> <select id="collection_menu" name="collection" style="display: none;"> <?php include "photo_gallery_functions.php"; media_type_choice ($media_type); ?> </select> </form> <br> <form action="../../PHP/photo_gallery_functions.php" method="get"> <select id="gallery_menu" name="gallery" style="display:none;"> <?php include "photo_gallery_functions.php"; collection_choice ($collection, media_type_gallery: $media_type_gallery) ?> </select> </form> <br> </div> <div class ="image_scrollbox_continer"> <div class="image_scrollbox" style="overflow: auto;"> <ul class = "image_gallery" id="image.gallery" style="display: none;"> <?php include "photo_gallery_functions.php"; thumbnailPreview ($media_type_gallery, $collection_gallery, $gallery_choice_gallery); ?> </ul> </div> </div> </div> </div> </div> </div> </body> <footer> <?php include "../../Website_Pages/Element_Pages/footer.php" ?> </footer> </html> // photo_gallery_funxtions.php <?php $media_type_gallery = "$media_type"; function media_type_choice ($media_type) { if ($media_type == "Photo") { $directoryPath= "/Images/Photo_Gallery/Pictures/"; $contents = scandir($directoryPath); $directories= array_filter ($contents, function ($item) use ($directoryPath) { return is_dir($directoryPath."/". $item) && $item !== "." && $item !=="..";}); foreach ($directories as $directory) { echo "<option id='photo_collection' name='photo_collection' value='$directory' onclick= showDropdownGallery()></option>"; } } else if ($media_type == "Video"); { $directoryPath= "/Video/Video_Gallery/Video"; $contents = scandir($directoryPath); $directories= array_filter ($contents, function ($item) use ($directoryPath) { return is_dir($directoryPath."/". $item) && $item !== "."&& $item !== "..";}); foreach ($directories as $directory) { echo "<option id='video_collection' name='video_collection' value='$directory' onclick= showDropdownGallery()></option>"; } } } function collection_choice ($collection, $media_type_gallery) { if ($media_type_gallery == "Photo") { $directoryPathGallery= "/Images/Photo_Gallery/$collection/"; } else if ($media_type_gallery == "Video"); { $directoryPathGallery= "/Video/Video_Gallery/$collection/"; } $contents = scandir($directoryPathGallery); $directoriesGallery= array_filter ($contents, function ($item) use ($directoryPathGallery) { return is_dir($directoryPathGallery."/". $item) && $item !== "."&& $item !== "..";}); foreach ($directoriesGallery as $directoryGallery) { echo "<option id='gallery_choice' name='gallery_choice' value='$directoryGallery' onclick=showThumbnails()>$directoryGallery</option>"; } } function thumbnailPreview ($media_type_gallery, $collection_gallery, $gallery_choice_gallery) { if ($media_type_gallery == "Photo") { $gallery_type = "/Images/Photo_Gallery/"; } else if ($media_type_gallery == "Video"); { $gallery_type= "/Video/Video_Gallery/"; } $directoryPathImage= "$gallery_type/Thumbnails/$collection_gallery/$gallery_choice_gallery/"; $contentsImage= scandir($directoryPathImage); $directoriesImage= array_filter ($contentsImage, function ($item) use ($directoryPathImage) { return is_file($directoryPathImage."/". $item) && $item !== "."&& $item !== "..";}); foreach ($directoriesImage as $directoryImage) { if ($media_type_gallery == "Photo") { $thumbnail = "<img src='/Images/Photo_Gallery/Thumbnails/$collection_gallery/$gallery_choice_gallery/$directoryImage.png' alt='$directoryImage' width='100px' height='100px'>"; echo "<a href='/Images/Photo_Gallery/Pictures/$collection_gallery/$gallery_choice_gallery/$directoryImage.png' target='_blank'>$thumbnail</a>"; } else if ($media_type_gallery == "Video"); { $videoThumbnail = "<img src='/Video/Video_Gallery/Thumbnails/$collection_gallery/$gallery_choice_gallery/$directoryImage.png' alt='$directoriesImage' width='100px' height='100px'>"; echo "<li id='thumbnail'><a href='/Video/Video_Gallery/Video/$collection_gallery/$gallery_choice_gallery/$directoriesImage.mp4 target='_blank'>$thumbnail</a></li>"; } } } ?>

In API response some keys values are not coming as expected

    <?php

namespace AppServicesFeed;

use AppRepositoriesPollPollRepositoryInterface;
use AppRepositoriesPostPostRepositoryInterface;
use IlluminateHttpResourcesJsonAnonymousResourceCollection;
use IlluminatePaginationLengthAwarePaginator;
use IlluminateSupportFacadesLog;

class FeedService implements FeedServiceInterface
{
    public function __construct(
        private PostRepositoryInterface $postRepository,
        private PollRepositoryInterface $pollRepository
    ) {}

    /** Send all feeds
     *
     * @param array $data The filtered data
     * @return array The feed array
     */
    public function getFeeds(array $data): array
    {
        $page = $data['page'] ?? config('data.pagination.default_page', 1);
        $limit = $data['limit'] ?? config('data.pagination.default_limit', 10);

        // Get paginated posts and polls (fetching only required records)
        $posts = $this->postRepository->getPosts($data);
        $polls = $this->pollRepository->getPolls($data);

        // Ensure collections exist and default to empty collections if null
        $postsCollection = isset($posts->collection) ? collect($posts->collection) : collect();
        $pollsCollection = isset($polls->collection) ? collect($polls->collection) : collect();

        // Merge and sort by combined_created_at
        $mergedFeed = $postsCollection->merge($pollsCollection)
            ->sortByDesc('combined_created_at')
            ->values();

        // Paginate the merged feed
        $total = $mergedFeed->count();
        $paginatedItems = $mergedFeed->slice(($page - 1) * $limit, $limit)->values();

        // Apply transformations **only on the paginated items**
        $startIndex = ($page - 1) * $limit; // Start index based on pagination

        $transformedFeed = $paginatedItems->map(function ($item) use (&$startIndex, $data) {
            // Ensure JSON is properly decoded as an **object**
            $item->show_user_details = json_decode($item->show_user_details, false);

            $item->is_shared = (bool) $item->is_shared;

            // Generate unique ID using type, ID, index, page, and limit
            $uniqueKey = "{$item->type}-{$item->id}-{$startIndex}-{$data['page']}-{$data['limit']}";
            $item->unique_id = hash('sha256', $uniqueKey);

            $startIndex++; // Increment index

            return $item; // Ensure transformation is applied
        });

        // Create the paginator
        $paginatedFeed = new LengthAwarePaginator(
            $transformedFeed, // Only transformed paginated items
            $total, // Total items count
            $limit, // Items per page
            $page, // Current page
            ['path' => request()->url(), 'query' => request()->query()] // Maintain query parameters
        );

        return [
            'post' => $paginatedFeed->items(), // Extract items directly
            'pagination' => [
                'total' => $paginatedFeed->total(),
                'per_page' => $paginatedFeed->perPage(),
                'current_page' => $paginatedFeed->currentPage(),
                'last_page' => $paginatedFeed->lastPage(),
                'from' => $paginatedFeed->firstItem(),
                'to' => $paginatedFeed->lastItem(),
            ],
        ];
    }
}

    /**
     * Send all posts
     *
     * @param array $data The filtered data
     * @return AnonymousResourceCollection The post collection
     */
    public function getPosts(array $data): AnonymousResourceCollection
    {
        $this->setPaginationAndOrderBy($data);

        $postableId = $data["postable_id"] ?? null;
        $postableType = $data["postable_type"] ?? null;

        $username = $data['username'] ?? null;

        // Fetch user ID from username
        $userId = null;
        if ($username) {
            $userId = $this->user->where('username', $username)->value('id');
        }

        // Original Posts with Creator's Name
        $originalPosts = $this->post
            ->select(
                'posts.*',
                DB::raw('posts.created_at as combined_created_at'),
                DB::raw("
                CASE 
                    WHEN posts.postable_type LIKE '%User' THEN users.username
                    WHEN posts.postable_type LIKE '%Club' THEN clubs.name
                    ELSE NULL
                END as show_user
            "),
                DB::raw("
                CASE 
                    WHEN posts.postable_type LIKE '%User' THEN CAST(
                        JSON_OBJECT(
                            'id', users.id,
                            'profile_image', users.profile_image,
                            'username', users.username,
                            'email', users.email,
                            'first_name', users.first_name,
                            'last_name', users.last_name,
                            'gender',
                                CASE 
                                    WHEN users.gender = 0 THEN 'Male'
                                    WHEN users.gender = 1 THEN 'Female'
                                    WHEN users.gender = 2 THEN 'Others'
                                    ELSE NULL
                                END
                        ) AS JSON
                    )
                    WHEN posts.postable_type LIKE '%Club' THEN CAST(
                        JSON_OBJECT(
                            'id', clubs.id,
                            'name', clubs.name,
                            'description', clubs.description
                        ) AS JSON
                    )
                    ELSE NULL
                END as show_user_details
            "),
                DB::raw("FALSE as is_shared") // Adding is_shared flag
            )
            ->leftJoin('users', function ($join) {
                $join->on('posts.postable_id', '=', 'users.id')
                    ->where('posts.postable_type', 'App\Models\User');
            })
            ->leftJoin('clubs', function ($join) {
                $join->on('posts.postable_id', '=', 'clubs.id')
                    ->where('posts.postable_type', 'App\Models\Club');
            });

        // Apply filters for `postable_id` and `postable_type`
        if ($postableId && $postableType) {
            $originalPosts->where('posts.postable_id', $postableId)
                ->where('posts.postable_type', $postableType);
        }

        // Apply filter for user posts if username exists
        if ($userId) {
            $originalPosts->where('posts.postable_id', $userId)
                ->where('posts.postable_type', 'App\Models\User');
        }

        // Shared Posts with Sharer's Username
        $sharedPosts = $this->post
            ->select(
                'posts.*',
                DB::raw('post_shares.created_at as combined_created_at'),
                'shared_users.username as show_user',
                DB::raw("
                    CAST(
                        JSON_OBJECT(
                            'id', shared_users.id,
                            'profile_image', shared_users.profile_image,
                            'username', shared_users.username,
                            'email', shared_users.email,
                            'first_name', shared_users.first_name,
                            'last_name', shared_users.last_name,
                            'gender',
                                CASE 
                                    WHEN shared_users.gender = 0 THEN 'Male'
                                    WHEN shared_users.gender = 1 THEN 'Female'
                                    WHEN shared_users.gender = 2 THEN 'Others'
                                    ELSE NULL
                                END
                        ) AS JSON
                    ) as show_user_details
                "),
                DB::raw("TRUE as is_shared") // Adding is_shared flag
            )
            ->join('post_shares', 'posts.id', '=', 'post_shares.post_id')
            ->join('users as shared_users', 'post_shares.user_id', '=', 'shared_users.id');

        // Apply filter for shared posts if username exists
        if ($userId) {
            $sharedPosts->where('post_shares.user_id', $userId);
        }

        // Combine Original Posts + Shared Posts using UNION
        $posts = $originalPosts
            ->unionAll($sharedPosts)
            ->orderByDesc('combined_created_at')
            // ->paginate($this->limit, ['*'], 'page', $this->page);
            ->get();

        // $startIndex = ($data['page'] - 1) * $data['limit']; // Start index based on pagination

        // // Handles JSON decoding
        // $posts->transform(function ($post) use ($startIndex, $data) {
        //     $post->show_user_details = json_decode($post->show_user_details, true);
        //     $post->is_shared = (bool) $post->is_shared; // Ensure boolean type

        //     // Generate unique ID using post ID, index, page, and limit
        //     $uniqueKey = "{$post->type}-{$post->id}-{$startIndex}-{$data['page']}-{$data['limit']}";

        //     // Generate unique ID using hash
        //     $post->unique_id = hash('sha256', $uniqueKey);

        //     $startIndex++; // Increment the index for next post

        //     return $post;
        // });

        // Load default relations
        $posts->load([
            'postMedias',
            'postable',
            'comments.commentable',
            'club'
        ]);

        return PostResource::collection($posts);
    }

    /**
     * Send all polls
     *
     * @param array $data The filtered data
     * @return AnonymousResourceCollection The poll collection
     */
    public function getPolls(array $data): AnonymousResourceCollection
    {
        $this->setPaginationAndOrderBy($data);

        $pollableId = $data['pollable_id'] ?? null;
        $pollableType = $data['pollable_type'] ?? null;

        $username = $data['username'] ?? null;

        // Fetch user ID from username
        $userId = null;
        if ($username) {
            $userId = $this->user->where('username', $username)->value('id');
        }

        // Original Polls with Creator's Name
        $originalPolls = $this->poll
            ->select(
                'polls.*',
                DB::raw('polls.created_at as combined_created_at'),
                DB::raw("
                CASE 
                    WHEN polls.pollable_type LIKE '%User' THEN users.username
                    WHEN polls.pollable_type LIKE '%Admin' THEN admins.name
                    WHEN polls.pollable_type LIKE '%Club' THEN clubs.name
                    ELSE NULL
                END as show_user
            "),
                DB::raw("
                CASE 
                    WHEN polls.pollable_type LIKE '%User' THEN CAST(
                        JSON_OBJECT(
                            'id', users.id,
                            'profile_image', users.profile_image,
                            'username', users.username,
                            'email', users.email,
                            'first_name', users.first_name,
                            'last_name', users.last_name,
                            'gender',
                                CASE 
                                    WHEN users.gender = 0 THEN 'Male'
                                    WHEN users.gender = 1 THEN 'Female'
                                    WHEN users.gender = 2 THEN 'Others'
                                    ELSE NULL
                                END
                        ) AS JSON
                    )
                    WHEN polls.pollable_type LIKE '%Admin' THEN CAST(
                        JSON_OBJECT(
                            'id', admins.id,
                            'name', admins.name,
                            'email', admins.email
                        ) AS JSON
                    )
                    WHEN polls.pollable_type LIKE '%Club' THEN CAST(
                        JSON_OBJECT(
                            'id', clubs.id,
                            'name', clubs.name,
                            'description', clubs.description
                        ) AS JSON
                    )
                    ELSE NULL
                END as show_user_details
            "),
                DB::raw("FALSE as is_shared") // Adding is_shared flag
            )
            ->leftJoin('users', function ($join) {
                $join->on('polls.pollable_id', '=', 'users.id')
                    ->where('polls.pollable_type', 'App\Models\User');
            })
            ->leftJoin('admins', function ($join) {
                $join->on('polls.pollable_id', '=', 'admins.id')
                    ->where('polls.pollable_type', 'App\Models\Admin');
            })
            ->leftJoin('clubs', function ($join) {
                $join->on('polls.pollable_id', '=', 'clubs.id')
                    ->where('polls.pollable_type', 'App\Models\Club');
            });

        // Apply filters for `postable_id` and `postable_type`
        if ($pollableId && $pollableType) {
            $originalPolls->where('polls.pollable_id', $pollableId)
                ->where('polls.pollable_type', $pollableType);
        }

        // Apply filter for user polls if username exists
        if ($userId) {
            $originalPolls->where('polls.pollable_id', $userId)
                ->where('polls.pollable_type', 'App\Models\User');
        }

        // Shared Polls with Sharer's Username
        $sharedPolls = $this->poll
            ->select(
                'polls.*',
                DB::raw('poll_shares.created_at as combined_created_at'),
                'shared_users.username as show_user',
                DB::raw("
                CAST(
                    JSON_OBJECT(
                        'id', shared_users.id,
                        'profile_image', shared_users.profile_image,
                        'username', shared_users.username,
                        'email', shared_users.email,
                        'first_name', shared_users.first_name,
                        'last_name', shared_users.last_name,
                        'gender',
                            CASE 
                                WHEN shared_users.gender = 0 THEN 'Male'
                                WHEN shared_users.gender = 1 THEN 'Female'
                                WHEN shared_users.gender = 2 THEN 'Others'
                                ELSE NULL
                            END
                    ) AS JSON
                ) as show_user_details
                "),
                DB::raw("TRUE as is_shared") // Adding is_shared flag
            )
            ->join('poll_shares', 'polls.id', '=', 'poll_shares.poll_id')
            ->join('users as shared_users', 'poll_shares.user_id', '=', 'shared_users.id');

        // Apply filter for shared polls if username exists
        if ($userId) {
            $sharedPolls->where('poll_shares.user_id', $userId);
        }

        // Combine Original Polls + Shared Polls using UNION
        $polls = $originalPolls
            ->unionAll($sharedPolls)
            ->orderByDesc('combined_created_at')
            //->paginate($this->limit, ['*'], 'page', $this->page);
            ->get();

        // $startIndex = ($data['page'] - 1) * $data['limit']; // Start index based on pagination

        // // Handles JSON decoding
        // $polls->transform(function ($poll) use ($startIndex, $data) {
        //     $poll->show_user_details = json_decode($poll->show_user_details, true);
        //     $poll->is_shared = (bool) $poll->is_shared; // Ensure boolean type

        //     // Generate unique ID using post ID, index, page, and limit
        //     $uniqueKey = "{$poll->type}-{$poll->id}-{$startIndex}-{$data['page']}-{$data['limit']}";

        //     // Generate unique ID using hash
        //     $poll->unique_id = hash('sha256', $uniqueKey);

        //     $startIndex++; // Increment the index for next post

        //     return $poll;
        // });

        // Load default relations
        $polls->load([
            'pollOptions',
            'pollable',
            'comments.commentable',
            'club',
        ]);

        return PollResource::collection($polls);
    }

Here we’ve an API /feeds?page=1&limit=10 and API response will be sent from the getFeeds function and we’re merging the post and poll data and after merging we apply the pagination.
In response of the API show_user_details not decoded properly.Instead of is_shared 0 or 1 in response false or true should come. And unique_id is not present in the response

How to update and delete records in a table based on a new request?

I need to update records for Guide Steps (Every recipe has steps/instruction and my table was created for storing this data)

I was able to create those records in the db with quite easy syntax:

GuideStep::insert($groupedSteps); // $groupedSteps is an array

But now I need to update those records (and remove unnecessary ones), for this moment I came up with logic that can only update records or create if there is no such records:

foreach ($groupedSteps as $step){
  GuideStep::updateOrInsert(
    ['recipe_id' => $recipeId, 'step_number' => $step['step_number']],
    ['step_text' => $step['step_text'], 'step_image' => $step['step_image']]
  );
}

migration:

Schema::create('guide_steps', function (Blueprint $table) {
            $table->id();
            $table->foreignId('recipe_id')->constrained()->cascadeOnDelete();
            $table->integer('step_number');
            $table->text('step_text');
            $table->string('step_image')->default('recipes-images/default/default_photo.png');
            $table->timestamps();
        });

I thought that I’ll be able to use upsert() but this method requires unique columns (I don’t have those)

Be grateful for some advices

PHP problem getting JSON POST after decrypting initial POST data

I have an Android app that POSTS data to a PHP server via Retrofit. The app uses encryption to send data to server. The encryption and decryption on the server works well.

I am now implementing a multipart POST in Retrofit for images. My tests are giving me an issue getting the JSON data after the decryption of the POST data happens.

Sample of what the message looks like before decrpytion:

{"message":"IPJqXxv3eI1HURLVEup+PXIoZ94vhsxCkvPEx8bhOXTV1iGmf89O...."}

Working example below without multipart data POST on PHP server:

    $data = json_decode(file_get_contents('php://input'));       

    $message = $data->{'message'};

    $json = $myUtils->decryptPost($message);

This is the relevent part of the decryption function:

    function decryptPost($message){

         ....

    $str = mb_convert_encoding($str, "UTF-8");

    $json = json_decode($str, true);

    return $json;
}

When I do the same with the multipart form data, $json is NULL.

What I have tried so far inside the end of the decryptPost function:

        $str = mb_convert_encoding($str, "UTF-8");

        echo $str;

This prints out the right data but I just can’t access it via JSON. The JSON name indicated in the app is labeled as “items”, which it is named properly.

> 2025-03-26 05:26:49.566 22294-22647 okhttp.OkHttpClient    
> com.itgeek25.syncourlists            I 
> --1dbcd23c-55d7-46aa-8801-422d2814fd62 2025-03-26 05:26:49.569 22294-22647 okhttp.OkHttpClient     com.itgeek25.syncourlists         
> I  Content-Disposition: form-data; name="items" 2025-03-26
> 05:26:49.570 22294-22647 okhttp.OkHttpClient    
> com.itgeek25.syncourlists            I  Content-Transfer-Encoding:
> binary 2025-03-26 05:26:49.571 22294-22647 okhttp.OkHttpClient    
> com.itgeek25.syncourlists            I  Content-Type:
> application/json; charset=UTF-8 2025-03-26 05:26:49.571 22294-22647
> okhttp.OkHttpClient     com.itgeek25.syncourlists            I 
> Content-Length: 182 2025-03-26 05:26:49.573 22294-22647
> okhttp.OkHttpClient     com.itgeek25.syncourlists            I  
> 2025-03-26 05:26:49.574 22294-22647 okhttp.OkHttpClient    
> com.itgeek25.syncourlists            I 
> {"category":"Books","deleted":[],"items":[{"id":71,"is_marked":1,"item":"Mistake"},{"id":72,"is_marked":1,"item":"Subardf"}],"list_id":147,"sol_id":-10,"title":"Something
> important"} 2025-03-26 05:26:49.574 22294-22647 okhttp.OkHttpClient   
> com.itgeek25.syncourlists            I 
> --1dbcd23c-55d7-46aa-8801-422d2814fd62--

Each approach returns either null or can’t access object in array:

$json = json_encode($str);
$json = json_decode($json, true);
echo $json['items'];
echo $json->{'items'};

Problems with complexity in dependency conditional injection with PHP-DI

I’m working on a PHP project where I’m using PHP-DI for dependency injection, but I’m struggling to configure a hierarchical structure of classes cleanly and scalably. I have interfaces like ParentLoader and ChildLoader, with concrete implementations for different types: XML (e.g., XmlParentLoader, XmlChildLoader) that depend on a DOMDocument, and SQL (e.g., SqlParentLoader, SqlChildLoader) that depend on a PDO. These loaders are hierarchical (ParentLoader depends on ChildLoader), and I need to inject them conditionally based on a configuration (e.g., "type" => "xml" or "type" => "sql" from a settings file) into a service that uses two ParentLoader instances.

Here’s a simplified example of my classes:

interface ParentLoader
{
    public function load(): array; // Just an example
}

interface ChildLoader
{
    public function load(): array; // Just an example
}

class XmlParentLoader implements ParentLoader
{
    public function __construct(private XmlChildLoader $childs, private DOMDocument $source)
    {
    }

    public function load(): array
    {
        // Logic using $source and $childs
        return [];
    }
}

class XmlChildLoader implements ChildLoader
{
    public function __construct(private DOMDocument $source)
    {
    }

    public function load(): array
    {
        // Logic using $source
        return [];
    }
}

class SqlParentLoader implements ParentLoader
{
    public function __construct(private SqlChildLoader $childs, private PDO $source)
    {
    }

    public function load(): array
    {
        // Logic using $source and $childs
        return [];
    }
}

class SqlChildLoader implements ChildLoader
{
    public function __construct(private PDO $source)
    {
    }

    public function load(): array
    {
        // Logic using $source
        return [];
    }
}

class MyService
{
    public function __construct(
        private ParentLoader $model, // Based on "model" from settings
        private ParentLoader $target  // Based on "target" from settings
    ) {
    }

    public function execute(): array
    {
        $dataModel = $this->model->load();
        $dataTarget = $this->target->load();
        // Combine or process data
        return array_merge($dataModel, $dataTarget);
    }
}

I’m using PHP-DI to conditionally inject these dependencies based on a configuration. For example, if the config specifies "model" => ["type" => "xml"], $model should use XmlParentLoader and XmlChildLoader with a DOMDocument; if "target" => ["type" => "sql"], $target should use SqlParentLoader and SqlChildLoader with a PDO. Here’s what I tried in my ContainerBuilder:

use DIContainerBuilder;
use PsrContainerContainerInterface;

$builder = new ContainerBuilder();
$builder->addDefinitions([
    'xml.source' => function () {
        $dom = new DOMDocument();
        $dom->load('some/path.xml'); // Simplified for example
        return $dom;
    },
    'sql.source' => function () {
        return new PDO('mysql:host=localhost;dbname=test', 'user', 'pass'); // Simplified
    },
    'parent.model' => function (ContainerInterface $container) {
        $settings = $container->get('settings'); // Assume settings has "model" and "target"
        $type = $settings['model']['type'];
        if ($type === 'xml') {
            return $container->get('xml.parent.loader.model');
        } elseif ($type === 'sql') {
            return $container->get('sql.parent.loader.model');
        }
        throw new Exception('Invalid type in model configuration');
    },
    'parent.target' => function (ContainerInterface $container) {
        $settings = $container->get('settings');
        $type = $settings['target']['type'];
        if ($type === 'xml') {
            return $container->get('xml.parent.loader.target');
        } elseif ($type === 'sql') {
            return $container->get('sql.parent.loader.target');
        }
        throw new Exception('Invalid type in target configuration');
    },
    'xml.parent.loader.model' => DIcreate(XmlParentLoader::class)
        ->constructor(DIget('xml.child.loader.model'), DIget('xml.source')),
    'xml.child.loader.model' => DIcreate(XmlChildLoader::class)
        ->constructor(DIget('xml.source')),
    'sql.parent.loader.model' => DIcreate(SqlParentLoader::class)
        ->constructor(DIget('sql.child.loader.model'), DIget('sql.source')),
    'sql.child.loader.model' => DIcreate(SqlChildLoader::class)
        ->constructor(DIget('sql.source')),
    'xml.parent.loader.target' => DIcreate(XmlParentLoader::class)
        ->constructor(DIget('xml.child.loader.target'), DIget('xml.source')),
    'xml.child.loader.target' => DIcreate(XmlChildLoader::class)
        ->constructor(DIget('xml.source')),
    'sql.parent.loader.target' => DIcreate(SqlParentLoader::class)
        ->constructor(DIget('sql.child.loader.target'), DIget('sql.source')),
    'sql.child.loader.target' => DIcreate(SqlChildLoader::class)
        ->constructor(DIget('sql.source')),
    MyService::class => DIcreate()
        ->constructor(DIget('parent.model'), DIget('parent.target'));
]);

This works, but it’s a mess. I have to manually define every loader in the hierarchy (e.g., xml.parent.loader.model, xml.child.loader.model, etc.) and their dependencies (DOMDocument or PDO) for each source (model and target). It gets worse when the hierarchy grows (e.g., adding a GrandChildLoader). My goal is a solution where I don’t need to manually define every loader and its dependencies in the DI container for each source and type combination, making use of autowire for example, which currently I can’t because of the “conditional injection”. If wasn’t for the “source” parameter, I would be able to use autowire, but I need the source.

Is there a better way to structure this with or without PHP-DI? Maybe a factory pattern or some trick to avoid these repetitive definitions? I’d love to leverage autowiring more, but the specific sources (DOMDocument and PDO) make it tricky. Any ideas would be awesome!

Thanks!

Run Gobgp commnad By Web Interface ( ubuntu server) [closed]

Hi i need php or other web languagues that have box ( ip address ) and two bottom ban or unban

if select ban fetch ip address from box and run shell script

script is gobgp global rib add -a ipv4 $ip/32 community 65000:666

If select unban fetch ip address from box and run this shell script

gobgp global rib del -a ipv4 $ip/32 community 65000:666

How to save image from front camera with input file type capture camera [closed]

I want to create a web application with a feature to take pictures from the front camera with html tag such as

  • html
<form id="data" method="post" enctype="multipart/form-data">
<input type="file" capture="camera" accept="image/*" class="btn btn-primary" 
       id="takePhoto" name="takePhoto" />
<input type="submit" id="submit" name="submit" class="btn btn-primary" value="Upload!" />
</form>

  • Javascript
       <script>
    
        $(document).ready(function(){
           $("form#data").submit(function(e) {
               e.preventDefault();    
               var formData = new FormData(this);

               $.ajax({
                  url:'https://example.com/proccess.php',
                  crossDomain: true,
                  type: 'POST',
                  data: formData,
                  success: function (data) {
                     alert(data)
                  },
                  cache: false,
                  contentType: false,
                  processData: false
               });
            });
        });
     </script>

  • php

….

            header("Access-Control-Allow-Origin: *");
            header('Access-Control-Allow-Methods: GET, POST, REQUEST');
     
            $folderPath = "uploads/";
        $tdate = date('d_m_Y_h_i_s');       
        $allowed_ext = array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf', 'rar', 'zip', 'jpg', 'jpeg', 'png');
        $file_name = $_FILES["takePhoto"]["name"];
        $file_temp = $_FILES["takePhoto"]["tmp_name"];
        $sourceProperties = getimagesize($file_temp);
             
             $fileNewName = $tdate;
             $ext = pathinfo($_FILES["takePhoto"]["name"], PATHINFO_EXTENSION);
             $getname = explode(".", $file_name);
         
             $ori_file = substr(str_replace(str_split('\/:*#?"<>|&+-;.()'), '_', $getname[0]),0);
             $ori_file = str_replace(" ","_",$ori_file);
         
             $file_name_exp = explode(".", $file_name);
         $file_ext = strtolower(array_pop($file_name_exp));
                = strtolower(end(explode('.', $file_name)));
         $file_size = $_FILES["takePhoto"]['size'];
         
             $file_name_up = $ori_file.'_'.$tdate.'.'.$file_ext;
                                
         if(in_array($file_ext, $allowed_ext) === true){
        
           $local = 'uploads/'.$file_name_up;
         
                  if (move_uploaded_file($file_tmp,$local)) {
                      echo "The file ". basename( $file_name_up) . " has been uploaded.<br>";
          
                        
                      if(rename($local, "/mnt/drive/server/uploads/".basename( $file_name_up))) {
                          echo "File moving operation success<br/>"; 
                       }
                       
                  } else {
                       echo "";
                  }
                            
         }else{
         echo '<div class="error">ERROR: Extentions not available!</div>';
         }              

If using the smartphone’s rear camera, the image can be saved, but if using the front camera, the image cannot be saved perfectly, whether because of the resolution or other things.

Symfony7 shared installations with cross repo and exclusive feature

I am trying to figure out what is the best approach to a reusable symfony application which has this key feature:

  • It uses a company shared private bundle which is being used in different projects (not just copies of the main app)
  • It has the main app which is the reusable one with optional feature that can be enabled via database
  • Each main app installation can have one or more extra feature bundle (which are extra private GIT repository). The key point here is that it may happen that for one installation i may want FeatureA to be in “beta mode” (so let’s say like a develop branch) while some other installation may still want the feature in “stable mode”. This would bring incoherence in my composer.json file and i can’t find any good solution to this issue.

For example let’s say my company shared private bundle is just a set of services that can handle some common utility tasks. The main app can be something like “stock management” then for some reason one installation may be needed to be used as a base for a book store, the other one for a shop center where each one has their own special needs to add extra feature around the base stock management layer

My question are:

  1. Has this approach have any sense at all? If not, what are the alternatives?
  2. If keeping everything separated as i said is doable, how should i handle different composer.json, assets (css/js), templates and more important symfony routes?

I would accept any answer that leads me to a solid, robust and maintainable long-term solution

I tried approaching the issue by creating 3 different repository: the shared private bundle, the main app and the feature bundle but i can’t seem to find the will to continue before i know if the decision made is solid enough to be used as base structure for the project

Performance Regression with Imagick between PHP 7.2 and 8.2

I’m noticing a significant performance difference when running the same Imagick script on PHP 7.2 versus PHP 8.2. Here are the results I’ve gathered:

  • PHP 7.2, ImageMagick 7.0.7, Imagick 3.44: 3.8 seconds

  • PHP 8.2, ImageMagick 7.1, Imagick 3.7: 13.32 seconds

Same spec machine, tested on windows and centos with similar results.

I’m wondering if anyone has encountered similar issues or knows why this change between PHP versions might be affecting Imagick’s performance so drastically? Or know any fixes for this? Below is the test script I’m using (it does this on other functions too not just distorts, this is just an example):

<?php

$startTime = microtime(true);

// Get script directory
$script_path = dirname(__FILE__) . "/";

$controlPoints = [
    1.5,
    0, 0, 355, 70,
    0, 3708, 337, 974,
    1380, 0, 657, 105,
    1380, 3708, 654, 956,
];

echo "Doing Distortion 1n";

$design = new Imagick($script_path . 'input.png');

// Apply distortion
try {
    $design->distortImage(Imagick::DISTORTION_POLYNOMIAL, $controlPoints, true);
} catch (Exception $e) {
    echo "Error applying distortion: " . $e->getMessage() . "n";
}

// Write the distorted image to an output file
$design->writeImage($script_path . "testoutput.png");

$endTime = microtime(true);
$executionTime = ($endTime - $startTime);

echo "Execution Time: " . $executionTime . " secondsn";

PHP variable as reference

I’m confused about the concept of variable in PHP.
As far as I know, a variable in PHP has a name ($p) and a value ('Carlo').

$p has an associated entry in symbol table, such an entry actually points to the memory area where the variable’s value is stored (i.e. the string 'Carlo').

Consider the following:

$n =& $p

$n basically is an alias of $p therefore it points to the memory area where $p points to.

From an “under the hood” viewpoint, does the PHP interpreter create a new entry in symbol table for $nor since it is an alias doesn’t have its own symbol table’s entry ?

Btw, suppose to define class Alpha with its properties and methods. Then does $c = new Alpha actually return a “reference” into the $c variable, in other words is $c value a reference in memory to an instance of class Alpha ?

Anyone has hints about what’s the problem here? – Laravel eager loading

simple example for my question

As you can see in the screenshot, there’s an error detected by Cursor IDE.

I specified the Model Contract as a type for a variable used in the function giveMeAContract.

But the problem is, at the function wtf() context,
the giveMeAContract() function seems to only want laravel query builder rather than a Model.

Problem is, the error message coming from the red underline says that you have to put a Model in it not the query builder. I think it’s exactly opposite of what I did.

Plus, it only happens when I eager load the collection.

Any hint for this? I solved it by a type hinting annotation but it is just temporary I guess.