php - Retrieve data from pivot table in laravel -


i new laravel. want show category a,b,c article id(1). showing id numbers 1,2,3 article id(i). spend few hours solution failed. want know how code correctly. , question is right way insert array db using implode().

category table -------------------- |    id | category | |     1 |        | |     2 |   b      | |     3 |   c      | |     4 |   d      | |     5 |   e      | --------------------  article_category ( pivot table ) ---------------------------- | article_id | category_id | |     1      |      1      | |     1      |      2      | |     1      |      3      | |     2      |      1      | |     2      |      5      | ---------------------------- 

html

@foreach( $categories $category )     <input type="checkbox" name="category[]" value="{{ $category->id }}" checked>&nbsp;{{ $category->category }}&nbsp;&nbsp; @endforeach 

laravel store

public function store(request $request)  {     $validator = validator::make($request->all(), [         'title' => 'required|unique:articles|max:255',         'content' => 'required',         'category' => 'required|max:100',         'status' => 'required|max:1'     ]);      if( $validator->passes() )       {         $category = implode(',', $request->category);         $articles = article::create([             'title' => $request->title,             'content' => $request->content,             'category' => $category,             'status' => $request->status,         ]);          $articles->categories()->sync($request->category);          return redirect($this->redirectto)                 ->with($this->key, $request->title.$this->storesuccess);     }     else      {         return redirect($this->redirectto.'/create')                 ->withinput($request->all())                 ->witherrors($validator);     } } 

first have define relationship in article model so

public function categories(){     return $this->belongstomany('modelnamewithnamespace'); } 

than can access

$categories = $article->category; foreach($categories $category) {     echo $category->{your field name}; } 

also should specify relation category article same way


Comments

Popular posts from this blog

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -