Laravel seeder - check if unique slug exists already











up vote
1
down vote

favorite












I am seeding a database table ('games') from several csv files. The table has a many-to-many-relationship with another table ('consoles'). The code works for the first csv file...



I am expecting to encounter duplicates (one game may release on multiple platforms).



Rather than an error exception, I would first like to check if the record (unique slug) already exists within the database table,
- if slug has already been used, just update relationships to existing record, syncing the pivot table against new console (I believe this is attach or sync?)
- if not - create a new record.



The model/schema is setup as such:



<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateGamesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('games', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('slug')->unique();


...



An example seeder code is



use IlluminateDatabaseSeeder;
use IlluminateDatabaseEloquentModel;
use IlluminateSupportStr;

class SnesGamesSeeder extends Seeder
{
public function run()
{

// Fetch the data from our CSV File
$data = $this->seedFromCSV(base_path('/database/seeds/csvs/snes-csv-filtered.csv'), ',');

foreach ($data as $game)
{
$title = $game['Title'];
$slug = Str::slug($title)
$date = strtotime($game['release_date']);
$format_date = date('Y-m-d',$date);

DB::table('games')->insert(
[
'title' => $title,
'slug' => $slug,
'release_date' => $format_date,

...


I would like to be able to do something like



   foreach ($data as $game)
{
$title = $game['Title'];
$slug = Str::slug($title)
**if(*** $slug already exists in 'game' table){
(find ID) -> ->consoles()->attach(5);
} else {**
DB::table('games')->insert(
[
'title' => $game['Title'],
'slug' => Str::slug($game['Title']),
'release_date' => $format_date,


...










share|improve this question




























    up vote
    1
    down vote

    favorite












    I am seeding a database table ('games') from several csv files. The table has a many-to-many-relationship with another table ('consoles'). The code works for the first csv file...



    I am expecting to encounter duplicates (one game may release on multiple platforms).



    Rather than an error exception, I would first like to check if the record (unique slug) already exists within the database table,
    - if slug has already been used, just update relationships to existing record, syncing the pivot table against new console (I believe this is attach or sync?)
    - if not - create a new record.



    The model/schema is setup as such:



    <?php

    use IlluminateSupportFacadesSchema;
    use IlluminateDatabaseSchemaBlueprint;
    use IlluminateDatabaseMigrationsMigration;

    class CreateGamesTable extends Migration
    {
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function up()
    {
    Schema::create('games', function (Blueprint $table) {
    $table->increments('id');
    $table->string('title');
    $table->string('slug')->unique();


    ...



    An example seeder code is



    use IlluminateDatabaseSeeder;
    use IlluminateDatabaseEloquentModel;
    use IlluminateSupportStr;

    class SnesGamesSeeder extends Seeder
    {
    public function run()
    {

    // Fetch the data from our CSV File
    $data = $this->seedFromCSV(base_path('/database/seeds/csvs/snes-csv-filtered.csv'), ',');

    foreach ($data as $game)
    {
    $title = $game['Title'];
    $slug = Str::slug($title)
    $date = strtotime($game['release_date']);
    $format_date = date('Y-m-d',$date);

    DB::table('games')->insert(
    [
    'title' => $title,
    'slug' => $slug,
    'release_date' => $format_date,

    ...


    I would like to be able to do something like



       foreach ($data as $game)
    {
    $title = $game['Title'];
    $slug = Str::slug($title)
    **if(*** $slug already exists in 'game' table){
    (find ID) -> ->consoles()->attach(5);
    } else {**
    DB::table('games')->insert(
    [
    'title' => $game['Title'],
    'slug' => Str::slug($game['Title']),
    'release_date' => $format_date,


    ...










    share|improve this question


























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      I am seeding a database table ('games') from several csv files. The table has a many-to-many-relationship with another table ('consoles'). The code works for the first csv file...



      I am expecting to encounter duplicates (one game may release on multiple platforms).



      Rather than an error exception, I would first like to check if the record (unique slug) already exists within the database table,
      - if slug has already been used, just update relationships to existing record, syncing the pivot table against new console (I believe this is attach or sync?)
      - if not - create a new record.



      The model/schema is setup as such:



      <?php

      use IlluminateSupportFacadesSchema;
      use IlluminateDatabaseSchemaBlueprint;
      use IlluminateDatabaseMigrationsMigration;

      class CreateGamesTable extends Migration
      {
      /**
      * Run the migrations.
      *
      * @return void
      */
      public function up()
      {
      Schema::create('games', function (Blueprint $table) {
      $table->increments('id');
      $table->string('title');
      $table->string('slug')->unique();


      ...



      An example seeder code is



      use IlluminateDatabaseSeeder;
      use IlluminateDatabaseEloquentModel;
      use IlluminateSupportStr;

      class SnesGamesSeeder extends Seeder
      {
      public function run()
      {

      // Fetch the data from our CSV File
      $data = $this->seedFromCSV(base_path('/database/seeds/csvs/snes-csv-filtered.csv'), ',');

      foreach ($data as $game)
      {
      $title = $game['Title'];
      $slug = Str::slug($title)
      $date = strtotime($game['release_date']);
      $format_date = date('Y-m-d',$date);

      DB::table('games')->insert(
      [
      'title' => $title,
      'slug' => $slug,
      'release_date' => $format_date,

      ...


      I would like to be able to do something like



         foreach ($data as $game)
      {
      $title = $game['Title'];
      $slug = Str::slug($title)
      **if(*** $slug already exists in 'game' table){
      (find ID) -> ->consoles()->attach(5);
      } else {**
      DB::table('games')->insert(
      [
      'title' => $game['Title'],
      'slug' => Str::slug($game['Title']),
      'release_date' => $format_date,


      ...










      share|improve this question















      I am seeding a database table ('games') from several csv files. The table has a many-to-many-relationship with another table ('consoles'). The code works for the first csv file...



      I am expecting to encounter duplicates (one game may release on multiple platforms).



      Rather than an error exception, I would first like to check if the record (unique slug) already exists within the database table,
      - if slug has already been used, just update relationships to existing record, syncing the pivot table against new console (I believe this is attach or sync?)
      - if not - create a new record.



      The model/schema is setup as such:



      <?php

      use IlluminateSupportFacadesSchema;
      use IlluminateDatabaseSchemaBlueprint;
      use IlluminateDatabaseMigrationsMigration;

      class CreateGamesTable extends Migration
      {
      /**
      * Run the migrations.
      *
      * @return void
      */
      public function up()
      {
      Schema::create('games', function (Blueprint $table) {
      $table->increments('id');
      $table->string('title');
      $table->string('slug')->unique();


      ...



      An example seeder code is



      use IlluminateDatabaseSeeder;
      use IlluminateDatabaseEloquentModel;
      use IlluminateSupportStr;

      class SnesGamesSeeder extends Seeder
      {
      public function run()
      {

      // Fetch the data from our CSV File
      $data = $this->seedFromCSV(base_path('/database/seeds/csvs/snes-csv-filtered.csv'), ',');

      foreach ($data as $game)
      {
      $title = $game['Title'];
      $slug = Str::slug($title)
      $date = strtotime($game['release_date']);
      $format_date = date('Y-m-d',$date);

      DB::table('games')->insert(
      [
      'title' => $title,
      'slug' => $slug,
      'release_date' => $format_date,

      ...


      I would like to be able to do something like



         foreach ($data as $game)
      {
      $title = $game['Title'];
      $slug = Str::slug($title)
      **if(*** $slug already exists in 'game' table){
      (find ID) -> ->consoles()->attach(5);
      } else {**
      DB::table('games')->insert(
      [
      'title' => $game['Title'],
      'slug' => Str::slug($game['Title']),
      'release_date' => $format_date,


      ...







      laravel seeding csv-import






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 11 at 0:39

























      asked Nov 11 at 0:25









      BeardyMrDeaks

      364




      364
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote













          You can use the first method:



          DB::table('game')->where('slug', $slug)->first();


          Example



          foreach ($data as $game) {
          $title = $game['Title'];
          $slug = Str::slug($title);

          if ($game = DB::table('game')->where('slug', $slug)->first()) {
          // update existing record
          } else {
          // insert new record
          }
          }


          If you've created the corresponding Eloquent models, the updateOrCreate method allows you to do:



          $attributes = ['foo' => 'bar'];

          // if a game exists with the given slug, update the attributes, otherwise create it.
          $game = Game::updateOrCreate(
          ['slug' => $slug],
          $attributes
          );





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53244738%2flaravel-seeder-check-if-unique-slug-exists-already%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            0
            down vote













            You can use the first method:



            DB::table('game')->where('slug', $slug)->first();


            Example



            foreach ($data as $game) {
            $title = $game['Title'];
            $slug = Str::slug($title);

            if ($game = DB::table('game')->where('slug', $slug)->first()) {
            // update existing record
            } else {
            // insert new record
            }
            }


            If you've created the corresponding Eloquent models, the updateOrCreate method allows you to do:



            $attributes = ['foo' => 'bar'];

            // if a game exists with the given slug, update the attributes, otherwise create it.
            $game = Game::updateOrCreate(
            ['slug' => $slug],
            $attributes
            );





            share|improve this answer



























              up vote
              0
              down vote













              You can use the first method:



              DB::table('game')->where('slug', $slug)->first();


              Example



              foreach ($data as $game) {
              $title = $game['Title'];
              $slug = Str::slug($title);

              if ($game = DB::table('game')->where('slug', $slug)->first()) {
              // update existing record
              } else {
              // insert new record
              }
              }


              If you've created the corresponding Eloquent models, the updateOrCreate method allows you to do:



              $attributes = ['foo' => 'bar'];

              // if a game exists with the given slug, update the attributes, otherwise create it.
              $game = Game::updateOrCreate(
              ['slug' => $slug],
              $attributes
              );





              share|improve this answer

























                up vote
                0
                down vote










                up vote
                0
                down vote









                You can use the first method:



                DB::table('game')->where('slug', $slug)->first();


                Example



                foreach ($data as $game) {
                $title = $game['Title'];
                $slug = Str::slug($title);

                if ($game = DB::table('game')->where('slug', $slug)->first()) {
                // update existing record
                } else {
                // insert new record
                }
                }


                If you've created the corresponding Eloquent models, the updateOrCreate method allows you to do:



                $attributes = ['foo' => 'bar'];

                // if a game exists with the given slug, update the attributes, otherwise create it.
                $game = Game::updateOrCreate(
                ['slug' => $slug],
                $attributes
                );





                share|improve this answer














                You can use the first method:



                DB::table('game')->where('slug', $slug)->first();


                Example



                foreach ($data as $game) {
                $title = $game['Title'];
                $slug = Str::slug($title);

                if ($game = DB::table('game')->where('slug', $slug)->first()) {
                // update existing record
                } else {
                // insert new record
                }
                }


                If you've created the corresponding Eloquent models, the updateOrCreate method allows you to do:



                $attributes = ['foo' => 'bar'];

                // if a game exists with the given slug, update the attributes, otherwise create it.
                $game = Game::updateOrCreate(
                ['slug' => $slug],
                $attributes
                );






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 11 at 2:01

























                answered Nov 11 at 1:54









                DigitalDrifter

                6,1112422




                6,1112422






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53244738%2flaravel-seeder-check-if-unique-slug-exists-already%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Florida Star v. B. J. F.

                    Danny Elfman

                    Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues