调用未定义的方法 stdClass::toJson()

Posted

技术标签:

【中文标题】调用未定义的方法 stdClass::toJson()【英文标题】:Call to undefined method stdClass::toJson() 【发布时间】:2019-11-20 18:16:06 【问题描述】:

我正在尝试观看有关如何在 laravel 中应用 websockets 以便拥有实时评论系统的视频,但我收到了这个错误,我不知道为什么。我遵循了他在系统中输入的每一个代码。有人知道我为什么会收到此错误?

shownews.blade.php

Comment Area
  <h4 class="comments-title" > <span class="fas fa-comment-alt"></span>
                    $news->comments()->count()
                    Comments</h4>
                  <div class="row" >
                      <div class="col-md-12 col-md-offset-2" style="overflow-y: scroll; height: 400px;
                      width: 400px; " id="commentarea" >

                          @foreach($news->comments as $comment)
                            <div class="comment" style="background-color: #f6efef;" >
                          <div class="author-info">
                              <img src="https://www.gravatar.com/avatar/" . md5(strtolower(trim($comment->email))) . "?s=50&d=retro"  class="author-image" id="image">

                              <div class="author-name">
                                   <h4>$comment->name </h4>
                                   <p class="author-time">   date('F nS, Y - g:iA' ,strtotime($comment->created_at)) </p>
                              </div>
                          </div>
                            <div class="comment-content">
                                    $comment->comment
                            </div>
                            </div>
                          @endforeach
                      </div>
                  </div>

Comment Form
       <div class="row">
                          <div class="col-md-4 col-12 form-group">
                          <label for="">Name</label>
                          <input type="text" placeholder="Name" v-model="username" required >
                          </div>
                          <div class="col-md-4 col-12 form-group">
                              <label>Email</label>
                           <input type="email" placeholder="Email" v-model="email" required >
                          </div>
                        </div>
                        <div class="row">
                          <div class="col-12 form-group">
                            <textarea class="form-control" cols="30" rows="10" placeholder="Comment" v-model="commentBox"></textarea>
                          </div>
                        </div>
                        <div class="form-submit">
                                <button class="btn btn-warning" style="margin-top:10px" @click.prevent="postComment">Save Comment</button>
                        </div>
                      -- </form> --

                    </div>
                  </div>

@section('scripts')

<script>
    const app = new Vue(
        el: '#app',
        data:
            comments:,
            commentBox = '',
            username = '',
            email = '',
            article:!! $news->toJson() !!,
        ,

        mounted()
            this.getComments();
        ,
        methods:
            getComments()
                axios.get(`/api/article/$this.news.id/comments`)
                    .then((response)=>
                        this.comments = response.data;
                    )
                    .catch(function(error)
                        console.log(error);
                    );
            ,
            postComment()
                axios.post(`/api/article/$this.news.id/comment`,
                    name: this.username,
                    email: this.email,
                    comment: this.commentBox
                )
                .then((response)=>
                    this.comments.unshift(response.data);
                    this.commentBox = '';
                )
                .catch(function(error)
                    console.log(error);
                );
            
        
    );
</script>
@endsection


CommentsController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Comment;
use App\News;
use App\Graph;
use Validator;
use Session;
use Response;

class CommentsController extends Controller

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(News $news)
    
        //
        return response()->json($news->comments());
    

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request, $news_id)
    
        //
        $this->validate($request, array(
            'name'=> 'required | max:255',
            'email'=> 'required| email | max:255',
            'comment'=> 'required | min:5'
        ));

        $news = News::find($news_id);

        $comment = new Comment();

        $comment->name = $request->name;
        $comment->email = $request->email;
        $comment->comment = $request->comment;
        $comment->approved = true;
        $comment->news()->associate($news);

        $comment->save();


        return $comment->toJson();

        // return redirect()->route('article', [$news->id]);
    



NewsController.php

<?php

namespace App\Http\Controllers;
use DB;
use Illuminate\Http\Request;
use App\News;
use Validator;
use Image;
use View;
use Storage;
use Illuminate\Support\Facades\Input;
use Response;
// use App\Http\Controllers\Controller;

class NewsController extends Controller


//Admin CRUD methods for news here. I diidnt include the code here because its for admin

    public function showNews($id)
    

        $all = DB::table('news')->get();
        $news = News::find($id);

        return View::make('coin.shownews', compact('news','all'));
    


api.php - 我跟着视频。他使用 api 路由以将数据作为 json 传递。

<?php
use Illuminate\Http\Request;

Route::get('article/id','NewsController@showNews');
Route::post('comments/news_id', 'CommentsController@store');

Route::middleware('auth:api')->group(function () 
);

web.php

//comments


//show Individual News with Comments
Route::group(['middleware'=>['web']], function()
    Route::get('/article/id', 'NewsController@showNews')->name('article');

);

Route::post('comments/news_id', ['uses' => 'CommentsController@store', 'as' => 'comments.store']);
Route::get('comments/id/edit',['uses'=>'CommentsController@edit', 'as' => 'comments.edit']);
Route::put('comments/id',['uses'=>'CommentsController@update', 'as' => 'comments.update']);
Route::delete('comments/id',['uses'=>'CommentsController@destroy', 'as' => 'comments.destroy']);

路线列表

+--------+-----------+------------------------+------------------+-------------------------------------------------------------------+------------+
| Domain | Method    | URI                    | Name             | Action                                                            | Middleware |
+--------+-----------+------------------------+------------------+-------------------------------------------------------------------+------------+
|        | GET|HEAD  | /                      |                  | App\Http\Controllers\GraphController@index                        | web        |
|        | GET|HEAD  | adminlogin             | login            | App\Http\Controllers\Auth\LoginController@showLoginForm           | web,guest  |
|        | POST      | adminlogin             |                  | App\Http\Controllers\Auth\LoginController@login                   | web,guest  |
|        | GET|HEAD  | api/article/id       |                  | App\Http\Controllers\NewsController@showNews                      | api        |
|        | POST      | api/comments/news_id |                  | App\Http\Controllers\CommentsController@store                     | api        |
|        | GET|HEAD  | article/id           | article          | App\Http\Controllers\NewsController@showNews                      | web        |
|        | PUT       | comments/id          | comments.update  | App\Http\Controllers\CommentsController@update                    | web        |
|        | DELETE    | comments/id          | comments.destroy | App\Http\Controllers\CommentsController@destroy                   | web        |
|        | GET|HEAD  | comments/id/edit     | comments.edit    | App\Http\Controllers\CommentsController@edit                      | web        |
|        | POST      | comments/news_id     | comments.store   | App\Http\Controllers\CommentsController@store                     | web        |
|        | GET|HEAD  | home                   | home             | App\Http\Controllers\HomeController@index                         | web        |
|        | GET|HEAD  | logout                 |                  | App\Http\Controllers\HomeController@logout                        | web        |
|        | GET|HEAD  | news                   | news.index       | App\Http\Controllers\NewsController@index                         | web        |
|        | POST      | news                   | news.store       | App\Http\Controllers\NewsController@store                         | web        |
|        | GET|HEAD  | news/create            | news.create      | App\Http\Controllers\NewsController@create                        | web        |
|        | PUT|PATCH | news/news            | news.update      | App\Http\Controllers\NewsController@update                        | web        |
|        | GET|HEAD  | news/news            | news.show        | App\Http\Controllers\NewsController@show                          | web        |
|        | DELETE    | news/news            | news.destroy     | App\Http\Controllers\NewsController@destroy                       | web        |
|        | GET|HEAD  | news/news/edit       | news.edit        | App\Http\Controllers\NewsController@edit                          | web        |
|        | GET|HEAD  | register               | register         | App\Http\Controllers\Auth\RegisterController@showRegistrationForm | web,guest  |
|        | POST      | register               |                  | App\Http\Controllers\Auth\RegisterController@register             | web,guest  |
|        | POST      | roadmap                | roadmap.store    | App\Http\Controllers\RoadmapController@store                      | web        |
|        | GET|HEAD  | roadmap                | roadmap.index    | App\Http\Controllers\RoadmapController@index                      | web        |
|        | GET|HEAD  | roadmap/create         | roadmap.create   | App\Http\Controllers\RoadmapController@create                     | web        |
|        | GET|HEAD  | roadmap/roadmap      | roadmap.show     | App\Http\Controllers\RoadmapController@show                       | web        |
|        | PUT|PATCH | roadmap/roadmap      | roadmap.update   | App\Http\Controllers\RoadmapController@update                     | web        |
|        | DELETE    | roadmap/roadmap      | roadmap.destroy  | App\Http\Controllers\RoadmapController@destroy                    | web        |
|        | GET|HEAD  | roadmap/roadmap/edit | roadmap.edit     | App\Http\Controllers\RoadmapController@edit                       | web        |
|        | GET|HEAD  | test                   |                  | App\Http\Controllers\GraphController@test                         | web        |
|        | GET|HEAD  | users                  | users.index      | App\Http\Controllers\UserController@index                         | web        |
|        | POST      | users                  | users.store      | App\Http\Controllers\UserController@store                         | web        |
|        | GET|HEAD  | users/create           | users.create     | App\Http\Controllers\UserController@create                        | web        |
|        | GET|HEAD  | users/user           | users.show       | App\Http\Controllers\UserController@show                          | web        |
|        | DELETE    | users/user           | users.destroy    | App\Http\Controllers\UserController@destroy                       | web        |
|        | PUT|PATCH | users/user           | users.update     | App\Http\Controllers\UserController@update                        | web        |
|        | GET|HEAD  | users/user/edit      | users.edit       | App\Http\Controllers\UserController@edit                          | web        |
+--------+-----------+------------------------+------------------+-------------------------------------------------------------------+------------+

【问题讨论】:

您收到一条错误消息。发生这种情况时,它往往会包括发生错误的文件和行号。请告诉我们发生错误的位置,并仅保留与问题直接相关的代码。现在,您已经发布了很多 代码,甚至没有指出错误发生的哪里。不要让我们经历这一切并猜测它发生在哪里...... 好的,对不起,先生。我认为这段代码article:!! $news-&gt;toJson() !! 给了我错误。对此先生有什么想法吗?它在我的刀片文件中。我不知道为什么会出现这个错误 有人可以帮我解决这个问题吗? 【参考方案1】:

您的$comment 变量是Object type。没有toJson property。如果您想将return 设为JSON,请使用response

return  response()->json(['comment' => $comment]);

【讨论】:

它仍然给我一个错误,先生。但是当我删除刀片文件中的article:!! $news-&gt;toJson() !! 代码时,它不会引发错误。但我无法检索或保存 cmets 我需要帮助 T_T

以上是关于调用未定义的方法 stdClass::toJson()的主要内容,如果未能解决你的问题,请参考以下文章

调用未定义的方法 App\Models\Catering::search() [关闭]

调用未定义的方法 BelongsTo::attach()

未调用自定义 UIButton 的 setIsSelected 方法

调用未定义的方法 Cake\ORM\Entity::query() CakePhp

致命错误:未捕获的错误:调用未定义的方法 stdClass::option();

调用类方法时出现“调用未定义函数”错误