Home > Software engineering >  Laravel pivot table and input field in edit blade
Laravel pivot table and input field in edit blade

Time:03-26

I have a small private project in Laravel. I have table articles, tags and pivot table (article_tag). I have tags and need to display them in the input field as a value for editing. I tried pluck() and find() but they don't work. I'm probably wrong somewhere but I don't see where. Tags should be a string? Or array? What statement should I write in the controller and what should I call for a view?

edit.blade.php

<h1 >Edit Post</h1>
<form method="POST" action="{{ route('articles.update', $article->id) }}" >
    @method('PUT')
    @csrf
    <div >
        <label for="tags" >Tags</label>
        <input type="text" name="tags"  value="{{-- $tags  --}}">
        @error('title')
            <div >{{ $message }}</div>
        @enderror
    </div>
    <button type="submit" >
        Update
    </button>
    <a href="{{ route('articles.show', $article->id) }}" >
        Cancel
    </a>
</form>

ArticleController.php


public function edit(Article $article)
{
    $tags = Tag::with('articles')->find('name'); // null
            
    return view('articles.edit', ['article' => $article, 'tags' => $tags]);
}

Tables

[articles]
id
title
body

[tags]
id
name

[article_tags]
id
tag_id
article_id

CodePudding user response:

Extending on the comments, hoping to nudge you in the right direction:

To get a collection/list of all tags you would do:

Tags::get();

To find a tag by id, you would do:

Tags::find($tagId);

To find a tag by name, assuming name is unique, you would do:

Tags::where('name', 'my-tag-name')->first();

To get a collection of all tag names, using pluck, you would do:

$tags = Tags::get();
$collectionOfTagNames = $tags->pluck('name');
$collectionOfTagNames->all(); //gives you the list of tag names

To get a collection of tag names with their associated ids as keys, you would do:

$tags = Tags::get();
$collectionOfTagNames = $tags->pluck('name', 'id');
$collectionOfTagNames->all();

And if you want all tags associated with the article, you COULD do this:

public function edit(Article $article)
{
  $tags = $article->tags()->get();
        
}

provided that your relationship is like this: in Article model:

public function tags(){
  return $this->belongsToMany(Tag::class);
}
  • Related