Laravel - Trying to get property 'id' of non-object

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');

Upvotes: 0

Views: 3198

Answers (2)

DOLWIN DAVIS
DOLWIN DAVIS

Reputation: 91

  public function create(){

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

Upvotes: 0

lagbox
lagbox

Reputation: 50491

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

Upvotes: 2

Related Questions