來自巴西的問候!試圖從數據透視表中取回數值
我有這個博客應用程序,和帖子有標籤。我做了多對多的關係,它可以很好地存儲,但編輯時無法取回它的值。
讓我們來看看一些代碼: 郵政型號
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function category()
{
return $this->belongsTo('App\Category');
}
public function tags()
{
return $this->belongsToMany('App\Tag');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
public function marca()
{
return $this->belongsToMany('App\Marca');
}
public function modelo()
{
return $this->belongsToMany('App\Modelo');
}
public function versao()
{
return $this->belongsToMany('App\Versao');
}
}
的PostController中@Create:
$post = new Post;
$post->title = $request->title;
$post->slug = $request->slug;
$post->category_id = $request->category_id;
$post->body = $request->body;
if ($request->hasFile('featured_image')){
$image = $request->file('featured_image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/' . $filename);
Image::make($image)->save($location);
$post->image = $filename;
}
$post->save();
$post->tags()->sync($request->tags, false);
而且PostController中@編輯:
public function edit($id)
{
$post = Post::find($id);
$categories = Category::all();
$tags = Tag::all();
$tags2 = array();
foreach ($tags as $tag) {
$tags2[$tag->id] = $tag->name;
}
$marcas = Marca::all();
$modelos = Modelo::all();
$versaos = Versao::all();
return view('manage.posts.edit')->withPost($post)->withCategories($categories)->withMarcas($marcas)->withTags($tags2)->withModelos($modelos)->withVersaos($versaos);
}
最後,但並非最不重要,HTML:
<label for="cambio">TAG</label>
<select class="custom-select select-multi" name="tags[]" multiple="multiple">
<option value="{{ $tags->id }}">{{ $tags->name }}</option>
</select>
<br>
<br>
的錯誤是:
(2/2) ErrorException
Trying to get property of non-object (View: /Users/marcellopato/Sites/CepCar2.0-BootStrap3.3/resources/views/manage/posts/edit.blade.php)
任何人,好嗎?
你好,你嘗試循環標籤? – Maraboc
不是。我曾經使用Form-Helpers做過這件事,但是因爲有點陳舊... –
試試我的答案! – Maraboc