简体   繁体   中英

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

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

  public function create(){

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM