0
votes

I have an error:

"Trying to get property 'id' of non-object (View: C:
xampp\htdocs\klikdesaku\resources\views\admin\posts\create.blade.php)"

I had used it without laravel collective form (i don't know its name)

example: {{!! Form::select() !!}}

This is my code:

create.blade.php

@foreach ($categories as $category )
   <option value="{{$category->id}}">{{$category->name}}</option>

PostController.php

public function create(){
        $this->authorize('create', Post::class);
        $categories = Category::pluck('name','id')->all();
        return view ('admin.posts.create', ['categories'=>$categories]);
    }

public function store(){
        $this->authorize('create', Post::class);
        $inputs = request()->validate([
            'title'=>'required',
            'post_image'=>'file'//mime: jpeg, png
            'body'=>'required',
            'category_id'=> 'required'
        ]);
        if(request('post_image')){
            $inputs['post_image'] = request('post_image')->store('images');
        }
        auth()->user()->posts()->create($inputs);
        session()->flash('post-create-message''Post was Created ' . $inputs['title']);
        return redirect()->route('post.index');
2
I think removing ->all() fix the issue. if it does not try @dd($categories) in your view. it will show you structure of $categories - Ts8060
Form:select requires at least two arguments and if you pass those arguments you won't need to loop in order to generate the options - apokryfos
removing ->all() didn't work either.... i try using @dd($categories), but it only display title and category in simple form.. - Mahardika Widya Kurniawan
@apokryfos: i didn't use Form:select but i use <select><option><\option><\select>... if i want to make Create Post using dropdown (category database).. in the PostController, what am i doing? - Mahardika Widya Kurniawan

2 Answers

2
votes

When calling pluck you are pulling a column, 'name', then indexing that value by a key, in this case 'id' (the second argument). When calling all on the Collection returned you get the underlying associative array. So your 'id' field is the key and the category 'name' is the value:

@foreach ($categories as $id => $name)
   <option value="{{ $id }}">{{ $name }}</option>
@endforeach

Even if you didn't call all and you have the Collection from pluck this would still work fine.

Laravel 8.x Docs - Database - Query Builder - Retrieving A List Of Column Values pluck

Laravel 8.x Docs - Collections - Available Methods - all

0
votes
  public function create(){

        $this->authorize('create', Post::class);
        $categories = Category::all(['name','id']);
        return view ('admin.posts.create')->with(['categories'=>$categories])
        
}