【问题标题】:Trying to get property of a non-object problem in laravel试图在laravel中获取非对象问题的属性
【发布时间】:2020-10-23 07:48:14
【问题描述】:

我正在做一个 laravel 项目。在这个项目中,如果非用户尝试编辑帖子,那么它将重定向到帖子页面,而不让用户进行任何编辑。但是我收到了这个错误

试图获取非对象的属性(查看:C:\xampp\htdocs\lsapp\resources\views\posts\show.blade.php)。

ErrorException (E_ERROR) Trying to get property of non-object (View: C:\xampp\htdocs\lsapp\resources\views\posts\show.blade.php)非对象的属性 (0) ErrorException {#221 ▼ #message: "尝试获取非对象的属性" #code: 0 #file: "C:\xampp\htdocs\lsapp\storage\framework\views\b4b78b7a31531d4e8ddf98112cc09d54ba62ed99 .php" #line: 3 #severity: E_NOTICE }

这里是编辑代码:

 public function edit($id)
    {
        $post = Post::find($id);
        if(auth()->user()->id !== $post->user_id){
            return redirect ('posts')->with('error','Unauthorized page');
        } 
        return view('posts.edit')->with('post',$post);
    }

PostsController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;
use DB;

class PostsController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth',['except'=>['index','show']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //$posts=Post::all();
        //$posts=Post::orderBy('title','desc')->get();
        //return Post::where('title','post two')->get();
        //$posts=DB::select("SELECT * FROM posts");
        //$posts= Post::orderBy('title','desc')->take(1)->get();
        $posts= Post::orderBy('created_at','desc')->paginate(1);
        
        return view('posts.index')->with('posts',$posts);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('posts.create');

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request,[
            'title'=>'required',
            'body'=>'required'
        ]);
        //Create posts
        $post=new Post;
        $post->title = $request->input('title');
        $post->body = $request->input('body');
        $post->user_id=auth()->user()->id;
        $post->save();

        return redirect('posts')->with('success','Post Created');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $post = Post::find($id); 
        return view('posts.show')->with('post',$post);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $post = Post::find($id);
        if(auth()->user()->id !== $post->user_id){
            return redirect ('posts')->with('error','Unauthorized page');
        } 
        return view('posts.edit')->with('post',$post);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request,[
            'title'=>'required',
            'body'=>'required'
        ]);
        //Create posts
        $post=Post::find($id);
        $post->title = $request->input('title');
        $post->body = $request->input('body');
        $post->save();

        return redirect('posts')->with('success','Post Updated');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */

    public function destroy($id)
    {
        $post=Post::find($id);
        $post->delete();
        return redirect('posts')->with('success','Post Deleted');

    }
}

show.blade.php:

@extends('layouts.app')

@section('content')
       <a href="{{route('posts.index')}}" class="btn btn-default">Back</a> 
       <h1>{{$post->title}}</h1>

       <div>
            {{$post->body}}
       </div>
       <hr>
       @if(!Auth::guest())
       @if(Auth::user()->id==$post->user_id)
       <small>Witten on {{$post->created_at}} by {{$post->user->name}}</small>

       <hr>
       <a href="{{$post->id}}/edit" class="btn btn-default">Edit</a>
       {!!Form::open(['action'=>['PostsController@destroy',$post->id],'method'=>'POST', 'class'=>'pull-right'])!!}
       {{Form::hidden('_method','DELETE')}}
       {{Form::submit('Delete',['class'=>'btn btn-danger'])}}
       {!!Form::close()!!}
       @endif

       @endif
       @endsection

这是我的路线:

Route::get('/index', 'PagesController@index');
Route::get('/about', 'PagesController@about');
Route::get('/services', 'PagesController@services');

Route::resource('/posts','PostsController');

Auth::routes();

Route::get('/dashboard', 'DashboardController@index');

这里是 user.php 以防万一

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function posts(){
        return $this->hasMany('App\Post');
    }
}

【问题讨论】:

  • 报错在文件的哪一行?
  • @dailysleaze 在这行 if(auth()->user()->id !== $post->user_id){ return redirect ('posts')->with('error' ,'未经授权的页面'); }
  • 错误似乎来自show.blade.php,而不是您的 PostsController。能否提供完整的错误信息?
  • @aynber ErrorException (E_ERROR) 试图获取非对象的属性(查看:C:\xampp\htdocs\lsapp\resources\views\posts\show.blade.php)以前的异常和可能可能有帮助 Trying to get property of non-object (0) ErrorException {#221 ▼ #message: "Trying to get property of non-object" #code: 0 #file: "C:\xampp\htdocs\lsapp\ storage\framework\views\b4b78b7a31531d4e8ddf98112cc09d54ba62ed99.php" #line: 3 #severity: E_NOTICE }
  • 请分享您的关系模型

标签: php laravel frameworks


【解决方案1】:

查看您的刀片文件。每当你所有的$post->user->SOMEPROPERTIES,把它改成$post->user['SOMEPROPERTIES']

例子:

   <small>Witten on {{$post->created_at}} by {{$post->user['name']}}</small>

我希望它对你有用。 (在我的情况下工作)

【讨论】:

    【解决方案2】:

    查看您的刀片文件。 无论何时你们都$post-&gt;user-&gt;SOMEPROPERTIES,改成$post-&gt;user()

    喜欢这里:

       <small>Witten on {{$post->created_at}} by {{$post->user()->name}}</small>
    

    【讨论】:

    • 它不工作。我认为问题出在 Back

      这一行。程序没有重定向到帖子页面。除了 PostsController 中的 edit() 之外,所有的 rediect 函数都在工作

    【解决方案3】:

    检查您的 href 值。检查花括号

    错误代码:

    @foreach($posts as $post)
        <a href="/posts/{$posts->id}">the text of the link</a>
    @endforeach
    

    工作代码:

    @foreach($posts as $post)
        <a href="/posts/{{$post->id}}">the text of the link</a>
    @endforeach
    

    我希望这在某种程度上有所帮助。

    【讨论】:

      猜你喜欢
      • 2018-06-27
      • 2019-03-27
      • 2015-08-19
      • 2018-02-21
      • 2015-09-22
      • 2017-03-20
      • 2014-03-25
      • 2015-01-25
      相关资源
      最近更新 更多