簡體   English   中英

未定義變量:注釋 - Laravel 5.8

[英]Undefined variable: comment - Laravel 5.8

當我想顯示我的新聞時,如果新聞沒有評論,我就會出錯。 但是當我想顯示帶有評論的新聞時,它會顯示新聞和評論。 你能猜出我的問題是什么嗎?

新聞控制器.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 App\Http\Controllers\Controller;

class NewsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $news = DB::table('news')->get();

        return view('news.index', ['news' => $news]);

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        return view('news.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, array(
            'title'=>'required|max:255',
            'body'=>'required',
            'subtitle'=>'required',
            // 'image'=>'required'
            'image' => 'image|mimes:jpeg,png,jpg,gif,svg,PNG|max:2048',
        ));

        // if($request->hasFile('image')){
        //     $request->image->store('public/img');
        //     // $news->save();
        //     $imageName = $request->image->store('public/img');
        // }



        $news = new News;
        $news->title = $request->title;
        $news->subtitle = $request->subtitle;
        $news->body = $request->body;
        // $news->image = $request->image;
        if ($request->hasFile('image')){
            //Add new photo
                $image = $request->file('image');
                $filename = time() . '.' . $image->getClientOriginalExtension();
                $location = public_path('img/' . $filename);
                Image::make($image)->resize(300,300)->save($location);

                $oldFilename = $news->image;
            //Update DB
                $news->image = $filename;

             //Delete the old photo
                // Storage::delete($oldFilename);
            }

        $news->save();

        return redirect()->route('news.index')->with('success','News created successfully');
        //  return view('news.index', $news);


    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //

        $news = News::find($id);
        return view('news.show', compact('news'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        $news = News::find($id);
        return view('news.edit', compact('news'));
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
        // request()->validate([
        //     'title' => 'required',
        //     'body' => 'required',
        //     'image' => 'required',
        //   ]);

        //   News::find($id)->update($request->all());
        $this->validate($request, array(
            'title'=>'required|max:255',
            'body'=>'required',
            'subtitle'=>'required',
            // 'image'=>'required'
            'image' => 'image|mimes:jpeg,png,jpg,gif,svg,PNG|max:2048',
        ));
        $news = News::find($id);

        // if($request->hasFile('image')){
        //     $request->image->store('public/img');
        //     // $news->save();
        //     $imageName = $request->image->store('public/img');
        // }

        $news->title = $request->title;
        $news->subtitle = $request->subtitle;
        $news->body = $request->body;
        // $news->image = $request->image;
        if ($request->hasFile('image')){
            //Add new photo
                $image = $request->file('image');
                $filename = time() . '.' . $image->getClientOriginalExtension();
                $location = public_path('img/' . $filename);
                Image::make($image)->resize(300,300)->save($location);

                $oldFilename = $news->image;
            //Update DB
                $news->image = $filename;

             //Delete the old photo
                // Storage::delete($oldFilename);
            }

        $news->save();
          return redirect()->route('news.index')->with('success','News updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        News::find($id)->delete();
        return redirect()->route('news.index')->with('success','News deleted successfully');
    }


    public function showNews($id)
    {

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

        $news = News::find($id);
       // return view('coin.shownews', compact('news'));
        return View::make('coin.shownews', compact('news','all'));
    }
}

評論控制器.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 App\Http\Controllers\Controller;

class NewsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $news = DB::table('news')->get();

        return view('news.index', ['news' => $news]);

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        return view('news.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, array(
            'title'=>'required|max:255',
            'body'=>'required',
            'subtitle'=>'required',
            // 'image'=>'required'
            'image' => 'image|mimes:jpeg,png,jpg,gif,svg,PNG|max:2048',
        ));

        // if($request->hasFile('image')){
        //     $request->image->store('public/img');
        //     // $news->save();
        //     $imageName = $request->image->store('public/img');
        // }



        $news = new News;
        $news->title = $request->title;
        $news->subtitle = $request->subtitle;
        $news->body = $request->body;
        // $news->image = $request->image;
        if ($request->hasFile('image')){
            //Add new photo
                $image = $request->file('image');
                $filename = time() . '.' . $image->getClientOriginalExtension();
                $location = public_path('img/' . $filename);
                Image::make($image)->resize(300,300)->save($location);

                $oldFilename = $news->image;
            //Update DB
                $news->image = $filename;

             //Delete the old photo
                // Storage::delete($oldFilename);
            }

        $news->save();

        return redirect()->route('news.index')->with('success','News created successfully');
        //  return view('news.index', $news);


    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //

        $news = News::find($id);
        return view('news.show', compact('news'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        $news = News::find($id);
        return view('news.edit', compact('news'));
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
        // request()->validate([
        //     'title' => 'required',
        //     'body' => 'required',
        //     'image' => 'required',
        //   ]);

        //   News::find($id)->update($request->all());
        $this->validate($request, array(
            'title'=>'required|max:255',
            'body'=>'required',
            'subtitle'=>'required',
            // 'image'=>'required'
            'image' => 'image|mimes:jpeg,png,jpg,gif,svg,PNG|max:2048',
        ));
        $news = News::find($id);

        // if($request->hasFile('image')){
        //     $request->image->store('public/img');
        //     // $news->save();
        //     $imageName = $request->image->store('public/img');
        // }

        $news->title = $request->title;
        $news->subtitle = $request->subtitle;
        $news->body = $request->body;
        // $news->image = $request->image;
        if ($request->hasFile('image')){
            //Add new photo
                $image = $request->file('image');
                $filename = time() . '.' . $image->getClientOriginalExtension();
                $location = public_path('img/' . $filename);
                Image::make($image)->resize(300,300)->save($location);

                $oldFilename = $news->image;
            //Update DB
                $news->image = $filename;

             //Delete the old photo
                // Storage::delete($oldFilename);
            }

        $news->save();
          return redirect()->route('news.index')->with('success','News updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        News::find($id)->delete();
        return redirect()->route('news.index')->with('success','News deleted successfully');
    }


    public function showNews($id)
    {

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

        $news = News::find($id);
       // return view('coin.shownews', compact('news'));
        return View::make('coin.shownews', compact('news','all'));
    }
}

Comment.php 模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{

    protected $fillable = [
        'name', 'email', 'comment',
    ];
    //
    public function news(){
        return $this->belongsTo('App\News');
    }
}

News.php 模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class news extends Model
{
    //
    protected $fillable = [
        'title', 'subtitle', 'body', 'image',
    ];


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

網頁.php

//comments
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']);

index.blade.php(新聞列表索引)

@extends('layouts.admin')




@section('content')

<meta name="csrf-token" content="{{ csrf_token() }}">
<!-- DATA TABLES -->
<script src="//code.jquery.com/jquery-1.12.3.js"></script>
<script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet"href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">


<div><a class="btn btn-success" style="float:right" href="{{ route('news.create') }}">Publish News</a></div>

<table id="myTable" class="table table-hover">
    <thead>
      <tr>
        <th scope="col">News ID</th>
        <th scope="col">News Title</th>
        <th scope="col">Date Posted</th>



        <th width="280px">Action</th>
      </tr>
    </thead>
    <tbody>
        @foreach ($news as $data)
        <tr>
           <td>{{ $data->id }}</td>
           <td>{{ $data->title }}</td>
           <td>{{ $data->created_at }}</td>


        <td>

        <a href="/news/{{$data->id}}/edit" class="btn btn-warning"><span class="glyphicon glyphicon-pencil"></span></a>

        <a href="/news/{{$data->id}}" class="btn btn-primary"><span class="glyphicon glyphicon-search"></span></a>

        {!! Form::open(['method' => 'DELETE', 'route'=>['news.destroy', $data->id], 'style'=> 'display:inline', 'onsubmit' => 'return confirm("Are you sure you want to delete?")']) !!}
        {!! Form::button('<i class="fa fa-trash"></i>',['type'=>'submit', 'class'=> 'btn btn-danger']) !!}
        {!! Form::close() !!}</td>


        </tr>
        @endforeach
    </tbody>
  </table>
  <script>
    $(document).ready(function() {
      $('#myTable').DataTable();

  } );
   </script>




@endsection

show.blade.php(帶有評論的新聞布局)

@extends('layouts.admin')

@section('content')


<div class="col-lg-12" >
        <div class="pull-center">
          <h3 >News Details </h3>
        </div>
      </div>
    </div>



<form>
        <div class="form-group">
                <label for="exampleInputPassword1">Image Displayed</label>
                ​<br>
                    <img src="{{ asset('img/' . $news->image) }}" class="img-fluid img-thumbnail"  />

          </div>
    <div class="form-group">
      <label for="exampleInputEmail1">News title</label>
      <textarea type="text" class="form-control" rows="1" disabled="true" id="exampleInputPassword1" placeholder=""> {{ $news->title }}</textarea>
      {{-- <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> --}}
    </div>
    <div class="form-group">
      <label for="exampleInputPassword1">Subtitle</label>
      <textarea type="text" class="form-control" rows="1" disabled="true" id="exampleInputPassword1" placeholder=""> {{ $news->subtitle }}</textarea>
    </div>
    <div class="form-group">
        <label for="exampleInputPassword1">Content</label>
        <textarea type="textarea" rows="5" disabled="true" class="form-control" > {{ $news->body }}</textarea>
      </div>

  </form>

  <div class="backend-comments">
        <table id="tables" class="table table-hover">
            <h3>Comments <small>{{$news->comments()->count()}}
            </small></h3>
                <thead>
                  <tr>
                    <th >Name</th>
                    <th >Email</th>
                    <th >Comment</th>
                    <th >Actions</th>
                  </tr>
                </thead>
                <tbody>
                    @foreach($news->comments as $comment)
                  <tr>
                  <th scope="row">{{$comment->name}}</th>
                    <td>{{$comment->email}}</td>
                    <td>{{$comment->comment}}</td>
                    <td>
                    <a href="{{route('comments.edit', $comment->id)}}" class="btn btn-xs btn-primary"><span class="glyphicon glyphicon-pencil"></span></a>

                    {{-- <a id="{{$comment->id}}" class="btn btn-xs btn-danger" data-toggle="modal" data-target="#exampleModalCenter_delete"><span class="glyphicon glyphicon-trash"></span></a> --}}

                    <button id="{{$comment->id}}" type="button" class="btn btn-xs btn-danger delete-data" data-toggle="modal" data-target="#exampleModalCenter_delete"><span class="glyphicon glyphicon-trash"></span></button>

                    </td>

                  </tr>
                  @endforeach
                </tbody>
              </table>


  <script>
        $(document).ready(function() {
          $('#tables').DataTable();

      } );
       </script>

    </div>

    <a class="btn btn-success" href="{{ route('news.index') }}">Return</a>





    <!-- delete modal -->
    <div class="modal fade bd-example-modal-sm" id="exampleModalCenter_delete" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="exampleModalCenterTitle">Confirmation</h5>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              </button>
              <form action="{{route('comments.destroy', $comment->id)}}">
                    {{method_field('delete')}}
                    {{csrf_field()}}
                </form>
            </div>
            <div class="modal-body">
          <p style="font-weight: bold; text-align: center;"> Do you want to delete the selected Comment? </p>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-primary" data-dismiss="modal">Back</button>
              <button type="button" class="btn btn-danger" id="delete-button">Delete</button>
            </div>
          </div>
        </div>
      </div>


  @endsection

@section('scripts')
      <script>
        $(document).ready(function(){

    });
      </script>


@endsection

我查看了您的代碼,發現您在show.blade.php modal (delete modal) 中使用了$comment這在此處不可用。

如果你想處理模態,你應該使用 JavaScript 否則你應該在每個評論旁邊包含刪除按鈕(因為$comment僅在你的 @foreach 中可用)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM