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

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript