John Davidson

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

0 comments
Message:


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


My Answer:
If you are trying to get a property in Laravel, you can do so by accessing the property using the arrow operator "->" on an object. Here is an example:

php
$user = User::find(1); // Assuming User is your model class
$name = $user->name; // Accessing the 'name' property of the user object


In this example, we are retrieving a user object from the database using the `find` method and then accessing the `name` property of that user object.

Make sure that the property you are trying to access is defined in the model class or the object you are working with.

Rate this post

4 of 5 based on 7458 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us