Laravel firstOrCreate without Eloquent












0















Eloquent has a firstOrCreate method which gets a model based on a condition, or creates it if it doesn't exist.



Is there any equivalent method in Laravel's query builder (i.e. NOT in Eloquent)? For example:



$row = DB::table('users')->where('user_id', 5)->firstOrCreate('name' => 'Peter', 'last_name' => 'Pan');



That would try to get a row from users with 'user_id'==5. If it doesn't exist, it would insert a row with that id number, plus the other mentioned fields.



EDIT: I'm not trying to apply my question with users. I used users as an example to make as clear as possible what I'm looking for.










share|improve this question




















  • 1





    Why you don't want to use Eloquent ?

    – MD. Jubair Mizan
    Nov 27 '18 at 20:01











  • I don't think so - you can check the builder source: laravel.com/api/5.7/Illuminate/Database/Query/Builder.html but you're unlikely to find it.

    – Joel Hinz
    Nov 27 '18 at 20:01











  • @MD.JubairMizan The example is a bit unfortunate, as users are quite appropriate for Eloquent. I'm actually trying to make a simple system for which I think it would be overkill to create a model in Eloquent.

    – Racso
    Nov 27 '18 at 20:05






  • 2





    @Racso a user model comes with Laravel. Seems pointless not to make use of it here. It's also very easy to create a model, Eloquent requires next to no configuration if you follow the conventions.

    – Devon
    Nov 27 '18 at 20:06


















0















Eloquent has a firstOrCreate method which gets a model based on a condition, or creates it if it doesn't exist.



Is there any equivalent method in Laravel's query builder (i.e. NOT in Eloquent)? For example:



$row = DB::table('users')->where('user_id', 5)->firstOrCreate('name' => 'Peter', 'last_name' => 'Pan');



That would try to get a row from users with 'user_id'==5. If it doesn't exist, it would insert a row with that id number, plus the other mentioned fields.



EDIT: I'm not trying to apply my question with users. I used users as an example to make as clear as possible what I'm looking for.










share|improve this question




















  • 1





    Why you don't want to use Eloquent ?

    – MD. Jubair Mizan
    Nov 27 '18 at 20:01











  • I don't think so - you can check the builder source: laravel.com/api/5.7/Illuminate/Database/Query/Builder.html but you're unlikely to find it.

    – Joel Hinz
    Nov 27 '18 at 20:01











  • @MD.JubairMizan The example is a bit unfortunate, as users are quite appropriate for Eloquent. I'm actually trying to make a simple system for which I think it would be overkill to create a model in Eloquent.

    – Racso
    Nov 27 '18 at 20:05






  • 2





    @Racso a user model comes with Laravel. Seems pointless not to make use of it here. It's also very easy to create a model, Eloquent requires next to no configuration if you follow the conventions.

    – Devon
    Nov 27 '18 at 20:06
















0












0








0








Eloquent has a firstOrCreate method which gets a model based on a condition, or creates it if it doesn't exist.



Is there any equivalent method in Laravel's query builder (i.e. NOT in Eloquent)? For example:



$row = DB::table('users')->where('user_id', 5)->firstOrCreate('name' => 'Peter', 'last_name' => 'Pan');



That would try to get a row from users with 'user_id'==5. If it doesn't exist, it would insert a row with that id number, plus the other mentioned fields.



EDIT: I'm not trying to apply my question with users. I used users as an example to make as clear as possible what I'm looking for.










share|improve this question
















Eloquent has a firstOrCreate method which gets a model based on a condition, or creates it if it doesn't exist.



Is there any equivalent method in Laravel's query builder (i.e. NOT in Eloquent)? For example:



$row = DB::table('users')->where('user_id', 5)->firstOrCreate('name' => 'Peter', 'last_name' => 'Pan');



That would try to get a row from users with 'user_id'==5. If it doesn't exist, it would insert a row with that id number, plus the other mentioned fields.



EDIT: I'm not trying to apply my question with users. I used users as an example to make as clear as possible what I'm looking for.







laravel






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 27 '18 at 20:07







Racso

















asked Nov 27 '18 at 19:57









RacsoRacso

1,5071818




1,5071818








  • 1





    Why you don't want to use Eloquent ?

    – MD. Jubair Mizan
    Nov 27 '18 at 20:01











  • I don't think so - you can check the builder source: laravel.com/api/5.7/Illuminate/Database/Query/Builder.html but you're unlikely to find it.

    – Joel Hinz
    Nov 27 '18 at 20:01











  • @MD.JubairMizan The example is a bit unfortunate, as users are quite appropriate for Eloquent. I'm actually trying to make a simple system for which I think it would be overkill to create a model in Eloquent.

    – Racso
    Nov 27 '18 at 20:05






  • 2





    @Racso a user model comes with Laravel. Seems pointless not to make use of it here. It's also very easy to create a model, Eloquent requires next to no configuration if you follow the conventions.

    – Devon
    Nov 27 '18 at 20:06
















  • 1





    Why you don't want to use Eloquent ?

    – MD. Jubair Mizan
    Nov 27 '18 at 20:01











  • I don't think so - you can check the builder source: laravel.com/api/5.7/Illuminate/Database/Query/Builder.html but you're unlikely to find it.

    – Joel Hinz
    Nov 27 '18 at 20:01











  • @MD.JubairMizan The example is a bit unfortunate, as users are quite appropriate for Eloquent. I'm actually trying to make a simple system for which I think it would be overkill to create a model in Eloquent.

    – Racso
    Nov 27 '18 at 20:05






  • 2





    @Racso a user model comes with Laravel. Seems pointless not to make use of it here. It's also very easy to create a model, Eloquent requires next to no configuration if you follow the conventions.

    – Devon
    Nov 27 '18 at 20:06










1




1





Why you don't want to use Eloquent ?

– MD. Jubair Mizan
Nov 27 '18 at 20:01





Why you don't want to use Eloquent ?

– MD. Jubair Mizan
Nov 27 '18 at 20:01













I don't think so - you can check the builder source: laravel.com/api/5.7/Illuminate/Database/Query/Builder.html but you're unlikely to find it.

– Joel Hinz
Nov 27 '18 at 20:01





I don't think so - you can check the builder source: laravel.com/api/5.7/Illuminate/Database/Query/Builder.html but you're unlikely to find it.

– Joel Hinz
Nov 27 '18 at 20:01













@MD.JubairMizan The example is a bit unfortunate, as users are quite appropriate for Eloquent. I'm actually trying to make a simple system for which I think it would be overkill to create a model in Eloquent.

– Racso
Nov 27 '18 at 20:05





@MD.JubairMizan The example is a bit unfortunate, as users are quite appropriate for Eloquent. I'm actually trying to make a simple system for which I think it would be overkill to create a model in Eloquent.

– Racso
Nov 27 '18 at 20:05




2




2





@Racso a user model comes with Laravel. Seems pointless not to make use of it here. It's also very easy to create a model, Eloquent requires next to no configuration if you follow the conventions.

– Devon
Nov 27 '18 at 20:06







@Racso a user model comes with Laravel. Seems pointless not to make use of it here. It's also very easy to create a model, Eloquent requires next to no configuration if you follow the conventions.

– Devon
Nov 27 '18 at 20:06














2 Answers
2






active

oldest

votes


















0














Nope, Laravel firstOrCreate is function, that says next:



public function firstOrCreate(array $attributes, array $values = )
{
if (! is_null($instance = $this->where($attributes)->first())) {
return $instance;
}

return tap($this->newModelInstance($attributes + $values), function ($instance) {
$instance->save();
});
}


But you can add it with query micro:



DB::query()->macro('firstOrCreate', function (array $attributes, array $values = )  
{
if ($record = $this->first()) {
// return model instance
}

// create model instance
});


So than you will be able to call it same way you do with Eloquent.



$record= DB::table('records')->where('alias', $alias)->firstOrFail();





share|improve this answer































    -2














    Yeah of course! Just use normal SQL and ->selectRaw( your conditions ) and look for if there is a entry where your specifications are.



    https://laravel.com/docs/5.7/queries#raw-expressions






    share|improve this answer
























    • How is a raw select comparable to firstOrCreate?

      – Devon
      Nov 27 '18 at 20:36











    • @Devon Because you can execute normal queries with raw? He said he wanted a non-eloquent way of doing

      – Aiden Kaiser
      Nov 27 '18 at 21:02











    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',
    autoActivateHeartbeat: false,
    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%2f53507197%2flaravel-firstorcreate-without-eloquent%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Nope, Laravel firstOrCreate is function, that says next:



    public function firstOrCreate(array $attributes, array $values = )
    {
    if (! is_null($instance = $this->where($attributes)->first())) {
    return $instance;
    }

    return tap($this->newModelInstance($attributes + $values), function ($instance) {
    $instance->save();
    });
    }


    But you can add it with query micro:



    DB::query()->macro('firstOrCreate', function (array $attributes, array $values = )  
    {
    if ($record = $this->first()) {
    // return model instance
    }

    // create model instance
    });


    So than you will be able to call it same way you do with Eloquent.



    $record= DB::table('records')->where('alias', $alias)->firstOrFail();





    share|improve this answer




























      0














      Nope, Laravel firstOrCreate is function, that says next:



      public function firstOrCreate(array $attributes, array $values = )
      {
      if (! is_null($instance = $this->where($attributes)->first())) {
      return $instance;
      }

      return tap($this->newModelInstance($attributes + $values), function ($instance) {
      $instance->save();
      });
      }


      But you can add it with query micro:



      DB::query()->macro('firstOrCreate', function (array $attributes, array $values = )  
      {
      if ($record = $this->first()) {
      // return model instance
      }

      // create model instance
      });


      So than you will be able to call it same way you do with Eloquent.



      $record= DB::table('records')->where('alias', $alias)->firstOrFail();





      share|improve this answer


























        0












        0








        0







        Nope, Laravel firstOrCreate is function, that says next:



        public function firstOrCreate(array $attributes, array $values = )
        {
        if (! is_null($instance = $this->where($attributes)->first())) {
        return $instance;
        }

        return tap($this->newModelInstance($attributes + $values), function ($instance) {
        $instance->save();
        });
        }


        But you can add it with query micro:



        DB::query()->macro('firstOrCreate', function (array $attributes, array $values = )  
        {
        if ($record = $this->first()) {
        // return model instance
        }

        // create model instance
        });


        So than you will be able to call it same way you do with Eloquent.



        $record= DB::table('records')->where('alias', $alias)->firstOrFail();





        share|improve this answer













        Nope, Laravel firstOrCreate is function, that says next:



        public function firstOrCreate(array $attributes, array $values = )
        {
        if (! is_null($instance = $this->where($attributes)->first())) {
        return $instance;
        }

        return tap($this->newModelInstance($attributes + $values), function ($instance) {
        $instance->save();
        });
        }


        But you can add it with query micro:



        DB::query()->macro('firstOrCreate', function (array $attributes, array $values = )  
        {
        if ($record = $this->first()) {
        // return model instance
        }

        // create model instance
        });


        So than you will be able to call it same way you do with Eloquent.



        $record= DB::table('records')->where('alias', $alias)->firstOrFail();






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 27 '18 at 20:53









        Yura HaliasYura Halias

        13




        13

























            -2














            Yeah of course! Just use normal SQL and ->selectRaw( your conditions ) and look for if there is a entry where your specifications are.



            https://laravel.com/docs/5.7/queries#raw-expressions






            share|improve this answer
























            • How is a raw select comparable to firstOrCreate?

              – Devon
              Nov 27 '18 at 20:36











            • @Devon Because you can execute normal queries with raw? He said he wanted a non-eloquent way of doing

              – Aiden Kaiser
              Nov 27 '18 at 21:02
















            -2














            Yeah of course! Just use normal SQL and ->selectRaw( your conditions ) and look for if there is a entry where your specifications are.



            https://laravel.com/docs/5.7/queries#raw-expressions






            share|improve this answer
























            • How is a raw select comparable to firstOrCreate?

              – Devon
              Nov 27 '18 at 20:36











            • @Devon Because you can execute normal queries with raw? He said he wanted a non-eloquent way of doing

              – Aiden Kaiser
              Nov 27 '18 at 21:02














            -2












            -2








            -2







            Yeah of course! Just use normal SQL and ->selectRaw( your conditions ) and look for if there is a entry where your specifications are.



            https://laravel.com/docs/5.7/queries#raw-expressions






            share|improve this answer













            Yeah of course! Just use normal SQL and ->selectRaw( your conditions ) and look for if there is a entry where your specifications are.



            https://laravel.com/docs/5.7/queries#raw-expressions







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 27 '18 at 20:12









            Aiden KaiserAiden Kaiser

            1076




            1076













            • How is a raw select comparable to firstOrCreate?

              – Devon
              Nov 27 '18 at 20:36











            • @Devon Because you can execute normal queries with raw? He said he wanted a non-eloquent way of doing

              – Aiden Kaiser
              Nov 27 '18 at 21:02



















            • How is a raw select comparable to firstOrCreate?

              – Devon
              Nov 27 '18 at 20:36











            • @Devon Because you can execute normal queries with raw? He said he wanted a non-eloquent way of doing

              – Aiden Kaiser
              Nov 27 '18 at 21:02

















            How is a raw select comparable to firstOrCreate?

            – Devon
            Nov 27 '18 at 20:36





            How is a raw select comparable to firstOrCreate?

            – Devon
            Nov 27 '18 at 20:36













            @Devon Because you can execute normal queries with raw? He said he wanted a non-eloquent way of doing

            – Aiden Kaiser
            Nov 27 '18 at 21:02





            @Devon Because you can execute normal queries with raw? He said he wanted a non-eloquent way of doing

            – Aiden Kaiser
            Nov 27 '18 at 21:02


















            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.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53507197%2flaravel-firstorcreate-without-eloquent%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

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

            Calculate evaluation metrics using cross_val_predict sklearn

            Insert data from modal to MySQL (multiple modal on website)