Search code examples
phpdatabaselaravelgithubcron

Laravel - Delete record from database if not exists in given array


I am fetching all my GitHub repositories using Campbells GitHub package for Laravel. I made a command and a cronjob which runs every minute and it works perfectly fine. The only problem is that when a repository gets deleted from GitHub it stays in my database instead of also getting deleted.

I came across a method called whereNotIn() which checks if the data does not meet the specified input and you can do actions to it accordingly. But I can't seem to make it work.

Say for instance this bottom table is a list of GitHub repos and my repos in my database

GitHub Repos.   |    Website repos

Repo 1          |    Repo 1
Repo 2          |    Repo 2
Repo 3          |    Repo 3
Repo 4          |    Repo 4
                |    Repo 5

You see that the list of GitHub repos is one short of the website repos, which means a repo got deleted on the GitHub side so in that case Repo 5 also needs to get deleted to stay up-to-date with the changes.

Handle method within the command

public function handle() {
        $repos = GitHub::connection('main')->me()->repositories();

        foreach($repos as $repo) {
            $name = str_replace(".", "-", $repo["name"]);

            Project::whereNotIn('name', $name)->delete();

            DB::table('projects')
                ->updateOrInsert(
                    ['name' => $name],
                    [
                        'name' => $name,
                        'html_url' => $repo["html_url"],
                        'description' => $repo["description"],
                        'stargazers_count' => $repo["stargazers_count"],
                        'language' => $repo["language"],
                    ]
                );
        }
}


Solution

  • You can do it as following:

    public function handle() {
        $repos = GitHub::connection('main')->me()->repositories();
        $existingReposNames = [];
    
        foreach($repos as $repo) {
            $name = str_replace(".", "-", $repo["name"]);
            $existingReposNames[] = $name;
            
    
            DB::table('projects')
                ->updateOrInsert(
                    ['name' => $name],
                    [
                        'name' => $name,
                        'html_url' => $repo["html_url"],
                        'description' => $repo["description"],
                        'stargazers_count' => $repo["stargazers_count"],
                        'language' => $repo["language"],
                    ]
                );
        }
    
        Project::whereNotIn('name', $existingReposNames)->delete();
    }