我得到一个错误未定义的变量(post).Iam使用Laravel框架

时间:2018-03-12 08:16:52

标签: php laravel controllers

我正在使用此函数将数据从数据库作为变量传递。 这是app.blade.php

    <!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
    <div id="app">
            @include('inc.navbar')

        <main class="py-4">

                <div class="container" style= "margin:20px" >
            @yield('content')
            @include('inc.messages')




        </main>
    </div>



    <!-- Scripts -->

    <script>
        document.addEventListener('DOMContentLoaded', inc);


    function inc(){ 
     var progress ={!! json_encode($post->progress, JSON_HEX_TAG) !!};
      percent=(progress/10)*100;
       document.getElementById('blue').style.width= percent+"%";
    }
    </script>



</body>
</html>

使用Post Controller在我的帖子页面上工作,但是当我想注销系统或注册时,我得到一个错误,说明未定义的变量(帖子)

这是帖子控制器的代码

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Post;

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::orderBy('created_at','desc')->paginate(10);
        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',
           'progress'=> 'required',
           'cover_image'=>'image|nullable|max:1999'

       ]);

        //handle file upload

        if($request->hasfile('cover_image')){
            //get filename with the extension
            $FilenameWithExt = $request->file('cover_image')->getClientOriginalName();
            //get just filename
            $filename = pathinfo($FilenameWithExt,PATHINFO_FILENAME);
            //get just ext
            $extension = $request->file('cover_image')->getClientOriginalExtension();
            //filename to store
            $fileNameToStore=$filename.'_'.time().'.'.$extension;
            //upload image
            $path =$request->file('cover_image')->storeAs('public/cover_images',$fileNameToStore);
        }else{
            $fileNameToStore = 'noimage.jpg';
        }

       //create post
       $post = new Post;
       $post->title = $request->input('title');
       $post->body = $request->input('body');
       $post->user_id = auth()->user()->id;
       $post->progress = $request->input('progress');
       $post->cover_image = $fileNameToStore;
       $post->save();

       return redirect('http://localhost/lsapp/public/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);

        //check for correct answer

        if(auth()->user()->id !==$post->user_id){
            return redirect('http://localhost/lsapp/public/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',
            'progress'=>'required',

        ]);
             //handle file upload

        if($request->hasfile('cover_image')){
            //get filename with the extension
            $FilenameWithExt = $request->file('cover_image')->getClientOriginalName();
            //get just filename
            $filename = pathinfo($FilenameWithExt,PATHINFO_FILENAME);
            //get just ext
            $extension = $request->file('cover_image')->getClientOriginalExtension();
            //filename to store
            $fileNameToStore=$filename.'_'.time().'.'.$extension;
            //upload image
            $path =$request->file('cover_image')->storeAs('public/cover_images',$fileNameToStore);
        }




        //create post
        $post =  Post::find($id);
        $post->title = $request->input('title');
        $post->body = $request->input('body');
        $post->progress=$request->input('progress');
        if($request->hasfile('cover_image')){
            $post->cover_image = $fileNameToStore;
        }
        $post->save();

        return redirect('http://localhost/lsapp/public/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);


        //check for correct answer

        if(auth()->user()->id !==$post->user_id){
            return redirect('http://localhost/lsapp/public/posts')->with('error', 'unauthorized page');

        }
        if($post->cover_image != 'noimage.jpg'){
            //delete image
            storage::delete('public/cover_images/'.$post->cover_image);


        }

        $post->delete();
        return redirect('http://localhost/lsapp/public/posts')->with('success','Post deleted');
    }
}

这是我的登录控制器中的代码

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/dashboard';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }


}

1 个答案:

答案 0 :(得分:0)

您的功能中存在拼写错误,其次将此功能移动到您的视图中,而不是在主视图中。

<sctipt>
    function inc(){ 
 var progress ={!! json_encode($posts->progress, JSON_HEX_TAG) !!};
  percent=(progress/10)*100;
   document.getElementById('blue').style.width= percent+"%";
}
</script>

在您的视图中将$post更改为$posts