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

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현