来自巴西的问候!试图从数据透视表中取回数值
我有这个博客应用程序,和帖子有标签。我做了多对多的关系,它可以很好地存储,但编辑时无法取回它的值。
让我们来看看一些代码: 邮政型号
<?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