Laravel polymorphic relation load model by morph name and foreign keyOne-to-many relationship without actual foreign keyLaravel Migration foreign key errorLaravel - Eloquent - Polymorphic relationships with namespacesLaravel Eloquent Relations: Saving two foreign keys at onceLaravel Polymorphic Relation for Product and Image-Laravel 5.2 insert logged in users foreign key automatically into product table when creating producttwo different foreign keys on one modelLaravel Eloquent. Same relation, different type of returnLaravel hasMany and belongsTo parametersLaravel - Polymorphic relationship not working

What do you call a notepad used to keep a record?

Different budgets within roommate group

What exactly did Ant-Man see that made him say that their plan worked?

How do we separate rules of logic from non-logical constraints?

How can I deal with extreme temperatures in a hotel room?

Why was Mal so quick to drop Bester in favour of Kaylee?

Who voices the character "Finger" in The Fifth Element?

Bin Packing with Relational Penalization

How can I tell what kind of genitals people have without gender?

Sacrifice blocking creature before damage is dealt no longer working (MtG Arena)?

Checkmate in 1 on a Tangled Board

What's the safest way to inform a new user of their password on an invite-only website?

What kind of jet plane is this?

Why is Japan trying to have a better relationship with Iran?

Movie with Zoltar in a trailer park named Paradise and a boy playing a video game then being recruited by aliens to fight in space

Is there reliable evidence that depleted uranium from the 1999 NATO bombing is causing cancer in Serbia?

Does Latin have any neuter words for humans?

Why did NASA wet the road in front of the Space Shuttle crawler?

Have any large aeroplanes been landed - safely and without damage - in locations that they could not be flown away from?

The warming up game

How do I tell the reader that my character is autistic in Fantasy?

I just started should I accept a farewell lunch for a coworker I don't know?

What verb for taking advantage fits in "I don't want to ________ on the friendship"?

Why would anyone even use a Portkey?



Laravel polymorphic relation load model by morph name and foreign key


One-to-many relationship without actual foreign keyLaravel Migration foreign key errorLaravel - Eloquent - Polymorphic relationships with namespacesLaravel Eloquent Relations: Saving two foreign keys at onceLaravel Polymorphic Relation for Product and Image-Laravel 5.2 insert logged in users foreign key automatically into product table when creating producttwo different foreign keys on one modelLaravel Eloquent. Same relation, different type of returnLaravel hasMany and belongsTo parametersLaravel - Polymorphic relationship not working






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am trying to create a comment to a commentable model (which is created by using polymorphic relations.) using the morphname key.



For example; i would like create a comment giving the morph name (blog) and foreign_key (1). But the morph name could change. So we don't know which key can be with the request. I don't want to create actions for each resource.



AppServiceProvider:



Relation::morphMap([
'blog' => AppModelsBlogBlogPost::class,
'product' => AppModelsCommerceProduct::class,
]);


Conroller -> action:



$this->validate($request, [
'commentable_model' => 'required|string',
'commentable_id' => 'required|integer|min:1',
'comment' => 'required|string'
]);

// i am trying to load data using morph name and foreign key here; but it's not working.
$model = $request->commentable_model::findOrFail($request->commentable_id);

$comment = new Comment;
$comment->comment = $request->comment;
$comment->commentable()->associate($model);
$comment->user()->associate(auth('api')->user());
$comment->save();


Commentable relation:



Schema::create('comments', function (Blueprint $table) 
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->text('comment');
$table->integer('parent_id')->unsigned()->nullable();
$table->foreign('parent_id')->references('id')->on('comments')->onDelete('cascade');
$table->morphs('commentable');
$table->timestamps();
);


Data:




commentable_model => 'blog',
commentable_id => 1




I will send these data via api endpoints. So, i would like to use just morhpnames, not full class names.



I could not get it work.



Any ideas?










share|improve this question
























  • How is it not working? Please add the commentable relationship.

    – Jonas Staudenmeir
    Mar 25 at 16:25











  • @JonasStaudenmeir Updated.

    – R. Canser Yanbakan
    Mar 26 at 6:24











  • What exactly isn't working? What's the result of dd($comment->getAttributes()) at the end?

    – Jonas Staudenmeir
    Mar 26 at 6:49











  • Actually i mentioned it above: $model = $request->commentable_model::findOrFail($request->commentable_id); this line. The idea is; use findOrFail method on given 'blog' (or any morph name) model.

    – R. Canser Yanbakan
    Mar 26 at 6:59

















0















I am trying to create a comment to a commentable model (which is created by using polymorphic relations.) using the morphname key.



For example; i would like create a comment giving the morph name (blog) and foreign_key (1). But the morph name could change. So we don't know which key can be with the request. I don't want to create actions for each resource.



AppServiceProvider:



Relation::morphMap([
'blog' => AppModelsBlogBlogPost::class,
'product' => AppModelsCommerceProduct::class,
]);


Conroller -> action:



$this->validate($request, [
'commentable_model' => 'required|string',
'commentable_id' => 'required|integer|min:1',
'comment' => 'required|string'
]);

// i am trying to load data using morph name and foreign key here; but it's not working.
$model = $request->commentable_model::findOrFail($request->commentable_id);

$comment = new Comment;
$comment->comment = $request->comment;
$comment->commentable()->associate($model);
$comment->user()->associate(auth('api')->user());
$comment->save();


Commentable relation:



Schema::create('comments', function (Blueprint $table) 
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->text('comment');
$table->integer('parent_id')->unsigned()->nullable();
$table->foreign('parent_id')->references('id')->on('comments')->onDelete('cascade');
$table->morphs('commentable');
$table->timestamps();
);


Data:




commentable_model => 'blog',
commentable_id => 1




I will send these data via api endpoints. So, i would like to use just morhpnames, not full class names.



I could not get it work.



Any ideas?










share|improve this question
























  • How is it not working? Please add the commentable relationship.

    – Jonas Staudenmeir
    Mar 25 at 16:25











  • @JonasStaudenmeir Updated.

    – R. Canser Yanbakan
    Mar 26 at 6:24











  • What exactly isn't working? What's the result of dd($comment->getAttributes()) at the end?

    – Jonas Staudenmeir
    Mar 26 at 6:49











  • Actually i mentioned it above: $model = $request->commentable_model::findOrFail($request->commentable_id); this line. The idea is; use findOrFail method on given 'blog' (or any morph name) model.

    – R. Canser Yanbakan
    Mar 26 at 6:59













0












0








0








I am trying to create a comment to a commentable model (which is created by using polymorphic relations.) using the morphname key.



For example; i would like create a comment giving the morph name (blog) and foreign_key (1). But the morph name could change. So we don't know which key can be with the request. I don't want to create actions for each resource.



AppServiceProvider:



Relation::morphMap([
'blog' => AppModelsBlogBlogPost::class,
'product' => AppModelsCommerceProduct::class,
]);


Conroller -> action:



$this->validate($request, [
'commentable_model' => 'required|string',
'commentable_id' => 'required|integer|min:1',
'comment' => 'required|string'
]);

// i am trying to load data using morph name and foreign key here; but it's not working.
$model = $request->commentable_model::findOrFail($request->commentable_id);

$comment = new Comment;
$comment->comment = $request->comment;
$comment->commentable()->associate($model);
$comment->user()->associate(auth('api')->user());
$comment->save();


Commentable relation:



Schema::create('comments', function (Blueprint $table) 
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->text('comment');
$table->integer('parent_id')->unsigned()->nullable();
$table->foreign('parent_id')->references('id')->on('comments')->onDelete('cascade');
$table->morphs('commentable');
$table->timestamps();
);


Data:




commentable_model => 'blog',
commentable_id => 1




I will send these data via api endpoints. So, i would like to use just morhpnames, not full class names.



I could not get it work.



Any ideas?










share|improve this question
















I am trying to create a comment to a commentable model (which is created by using polymorphic relations.) using the morphname key.



For example; i would like create a comment giving the morph name (blog) and foreign_key (1). But the morph name could change. So we don't know which key can be with the request. I don't want to create actions for each resource.



AppServiceProvider:



Relation::morphMap([
'blog' => AppModelsBlogBlogPost::class,
'product' => AppModelsCommerceProduct::class,
]);


Conroller -> action:



$this->validate($request, [
'commentable_model' => 'required|string',
'commentable_id' => 'required|integer|min:1',
'comment' => 'required|string'
]);

// i am trying to load data using morph name and foreign key here; but it's not working.
$model = $request->commentable_model::findOrFail($request->commentable_id);

$comment = new Comment;
$comment->comment = $request->comment;
$comment->commentable()->associate($model);
$comment->user()->associate(auth('api')->user());
$comment->save();


Commentable relation:



Schema::create('comments', function (Blueprint $table) 
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->text('comment');
$table->integer('parent_id')->unsigned()->nullable();
$table->foreign('parent_id')->references('id')->on('comments')->onDelete('cascade');
$table->morphs('commentable');
$table->timestamps();
);


Data:




commentable_model => 'blog',
commentable_id => 1




I will send these data via api endpoints. So, i would like to use just morhpnames, not full class names.



I could not get it work.



Any ideas?







laravel eloquent polymorphism






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 26 at 6:24







R. Canser Yanbakan

















asked Mar 25 at 14:02









R. Canser YanbakanR. Canser Yanbakan

2,6152 gold badges26 silver badges57 bronze badges




2,6152 gold badges26 silver badges57 bronze badges












  • How is it not working? Please add the commentable relationship.

    – Jonas Staudenmeir
    Mar 25 at 16:25











  • @JonasStaudenmeir Updated.

    – R. Canser Yanbakan
    Mar 26 at 6:24











  • What exactly isn't working? What's the result of dd($comment->getAttributes()) at the end?

    – Jonas Staudenmeir
    Mar 26 at 6:49











  • Actually i mentioned it above: $model = $request->commentable_model::findOrFail($request->commentable_id); this line. The idea is; use findOrFail method on given 'blog' (or any morph name) model.

    – R. Canser Yanbakan
    Mar 26 at 6:59

















  • How is it not working? Please add the commentable relationship.

    – Jonas Staudenmeir
    Mar 25 at 16:25











  • @JonasStaudenmeir Updated.

    – R. Canser Yanbakan
    Mar 26 at 6:24











  • What exactly isn't working? What's the result of dd($comment->getAttributes()) at the end?

    – Jonas Staudenmeir
    Mar 26 at 6:49











  • Actually i mentioned it above: $model = $request->commentable_model::findOrFail($request->commentable_id); this line. The idea is; use findOrFail method on given 'blog' (or any morph name) model.

    – R. Canser Yanbakan
    Mar 26 at 6:59
















How is it not working? Please add the commentable relationship.

– Jonas Staudenmeir
Mar 25 at 16:25





How is it not working? Please add the commentable relationship.

– Jonas Staudenmeir
Mar 25 at 16:25













@JonasStaudenmeir Updated.

– R. Canser Yanbakan
Mar 26 at 6:24





@JonasStaudenmeir Updated.

– R. Canser Yanbakan
Mar 26 at 6:24













What exactly isn't working? What's the result of dd($comment->getAttributes()) at the end?

– Jonas Staudenmeir
Mar 26 at 6:49





What exactly isn't working? What's the result of dd($comment->getAttributes()) at the end?

– Jonas Staudenmeir
Mar 26 at 6:49













Actually i mentioned it above: $model = $request->commentable_model::findOrFail($request->commentable_id); this line. The idea is; use findOrFail method on given 'blog' (or any morph name) model.

– R. Canser Yanbakan
Mar 26 at 6:59





Actually i mentioned it above: $model = $request->commentable_model::findOrFail($request->commentable_id); this line. The idea is; use findOrFail method on given 'blog' (or any morph name) model.

– R. Canser Yanbakan
Mar 26 at 6:59












1 Answer
1






active

oldest

votes


















0














I found the solution and it was in front of my eyes all the time actually...



We are making the mapping using the Relation class.



I have checked if can we access the relations with any method or variables and the answer is yes.



The short answer is;



Relation::$morphMap


returns all the mapping as an array.



And my solution for the question is;



$model = Relation::$morphMap[$request->commentable_model]::findOrFail($request->commentable_id);


Accessing that array value using our given morph name (which is blog).






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',
    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%2f55339591%2flaravel-polymorphic-relation-load-model-by-morph-name-and-foreign-key%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









    0














    I found the solution and it was in front of my eyes all the time actually...



    We are making the mapping using the Relation class.



    I have checked if can we access the relations with any method or variables and the answer is yes.



    The short answer is;



    Relation::$morphMap


    returns all the mapping as an array.



    And my solution for the question is;



    $model = Relation::$morphMap[$request->commentable_model]::findOrFail($request->commentable_id);


    Accessing that array value using our given morph name (which is blog).






    share|improve this answer



























      0














      I found the solution and it was in front of my eyes all the time actually...



      We are making the mapping using the Relation class.



      I have checked if can we access the relations with any method or variables and the answer is yes.



      The short answer is;



      Relation::$morphMap


      returns all the mapping as an array.



      And my solution for the question is;



      $model = Relation::$morphMap[$request->commentable_model]::findOrFail($request->commentable_id);


      Accessing that array value using our given morph name (which is blog).






      share|improve this answer

























        0












        0








        0







        I found the solution and it was in front of my eyes all the time actually...



        We are making the mapping using the Relation class.



        I have checked if can we access the relations with any method or variables and the answer is yes.



        The short answer is;



        Relation::$morphMap


        returns all the mapping as an array.



        And my solution for the question is;



        $model = Relation::$morphMap[$request->commentable_model]::findOrFail($request->commentable_id);


        Accessing that array value using our given morph name (which is blog).






        share|improve this answer













        I found the solution and it was in front of my eyes all the time actually...



        We are making the mapping using the Relation class.



        I have checked if can we access the relations with any method or variables and the answer is yes.



        The short answer is;



        Relation::$morphMap


        returns all the mapping as an array.



        And my solution for the question is;



        $model = Relation::$morphMap[$request->commentable_model]::findOrFail($request->commentable_id);


        Accessing that array value using our given morph name (which is blog).







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 26 at 9:01









        R. Canser YanbakanR. Canser Yanbakan

        2,6152 gold badges26 silver badges57 bronze badges




        2,6152 gold badges26 silver badges57 bronze badges


















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















            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%2f55339591%2flaravel-polymorphic-relation-load-model-by-morph-name-and-foreign-key%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

            How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

            Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?