Laravel:一个表与另一个表没有关系

时间:2019-01-30 14:46:33

标签: php laravel

我想更新“事件”表中的记录,但“事件”表与另一个表没有关系
那我该怎么做

这是我的代码和说明

<td>
    <a href="{{ route('events.edit',$event->id)}}">
        <span class="glyphicon glyphicon-edit"></span>
    </a>
</td>

我正在将$ event-> id发送到edit.blade.php页面以进行编辑请求

<form role="form" action="{{ route('events.update',$event->id)}}" method="post" enctype="multipart/form-data">

  {{csrf_field()}}

  {{method_field('PATCH')}}

  <div class="box-body">

    <div class="col-lg-6">

      <div class="box-body">

    <div class="col-lg-6">

     <div class="form-group">
      <label for="title">Event Title</label>
      <input type="text" name="title" class="form-control" id="title" placeholder="Title"
        value="{{$event->title}}">
    </div>

    <div class="form-group">
      <label for="subtitle">Place</label>
      <input type="text" name="place" class="form-control" id="place" placeholder="Place the Destination"
     value="{{$event->place}}" >
    </div>

此表单正在接收$ event-> id请求,但是当我运行此代码时,会发生此错误

“未定义变量:事件(视图:F:\ society \ resources \ views \ admin \ events \ edit.blade.php)”

这是事件控制器

public function edit($id)
{
    $events = event::where('id',$id)->first();
    return view('admin.events.edit',compact('events'));
}

更新功能在这里

public function update(Request $request, $id)
{
     $this->validate($request,[

        'title'=>'required',
        'place'=>'required',
        'starttime'=>'required',
        'endtime'=>'required',
        'datepicker'=>'required',
        'body'=>'required',
        'image'=>'required'

    ]);
    if($request->hasFile('image')){
        $img = $request->file('image');
        $filename = time() . '.' . $img->getClientOriginalExtension();
        Image::make($img)->resize(300, 300)->save( public_path('/uploads/avatars/' . $filename ) );

    }

    $event=event::find($id);
    $event->image= $filename;
    $event->title =$request->title;
    $event->place =$request->place;
    $event->starttime =$request->starttime;
    $event->endtime =$request->endtime;
    $event->datepicker =$request->datepicker;
    $event->body =$request->body;
    $event->save();
    return redirect(route('events.index'));
}

模型在这里

use Illuminate\Database\Eloquent\Model;

class event extends Model
{
    protected $table = 'events';

    public function events()
    {
        return $this->belongsTo(event::class);
    }
}

请告诉我问题出在哪里 模型或其他地方出现问题

1 个答案:

答案 0 :(得分:2)

您的控制器代码应如下所示:

public function edit($id)
{
    $event = event::findOrFail($id)
    return view('admin.events.edit', compact('event'));
}

您正在传递变量events而不是event