所以我有一个看起来像这样的表格:
@csrf
<div class="row">
@if ($errors->any())
<div class="alert alert-danger mt-2" role="alert">
<strong>{{ implode('', $errors->all(':message')) }}</strong>
</div>
@endif
</div>
<div class="form-group">
<label for="projectTitle">Project title</label>
<input type="text" class="form-control" name="proj_title" value="{{old('proj_title',$project->proj_title)}}">
</div>
<div class="form-group">
<label for="projectDesc">Description</label>
<textarea class="form-control" name="proj_desc" value="{{old('proj_desc',$project->proj_desc)}}"></textarea>
</div>
<div class="form-group">
<label for="clientId">Client Id</label>
<select name="client_id" class="form-control">
<option>1</option>
</select>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Create</button>
</div>
如您所见,用户需要输入项目标题,项目描述和客户ID。 然后,我有一个索引页面,您可以在其中查看项目,并且看起来像这样
@extends('layouts.app')
@section('content')
@if (Auth::user()->role == 1)
<a class="btn btn-secondary" href="/projects/create">Add Project</a>
@endif
<br><br>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Project Id</th>
<th>Title</th>
<th>Description</th>
<th>Client Id</th>
<th>Created by</th>
<th>Created on</th>
</tr>
</thead>
<tbody class="">
@foreach ($project as $project)
<tr>
<td>{{$project->proj_id}}</td>
<td>{{$project->proj_title}}</td>
<td>{{$project->proj_desc}}</td>
<td>{{$project->client_id}}</td>
<td>{{$project->created_by}}</td>
<td>{{$project->created_at}}</td>
</tr>
@endforeach
</tbody>
</table>
@endsection
我的意图是,它会自动获取登录用户的名称,并将其放在“创建者”字段中,我编写的代码就是这个
public function store(Request $r)
{
$validatedData = $r->validate([
'proj_title' => 'required|max:100',
'client_id' => 'required',
'proj_desc' => 'required',
]);
$currentUser = Auth::user()->name;
$r['created_by'] = $currentUser;
(new Project($r->all()))->save();
return redirect('/projects')->with('store','');
}
我测试了返回$ r数组,它在数组的正确索引中具有正确的名称,但是我不知道为什么它不进入数据库。
预先感谢
答案 0 :(得分:0)
不要忘记通过以下方式正确设置模型:
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
];
/**
* The attributes that should be hidden for arrays.
*
* @var string[]
*/
protected $hidden = [
];
您的created_by
字段必须是User
的外键,这样您就可以在迁移过程中做到这一点:
$table->integer('created_by');
$table->foreign('created_by')
->references('id')
->on('users')
->onDelete('cascade')
->onUpdate('cascade');
在您的Project
模型中建立belongsTo
关系:
/**
* Get the user that owns the phone.
*/
public function creator()
{
return $this->belongsTo(User::class);
}
请参阅: laravel.com/docs/5.8/eloquent-relationships#one-to-many
替换:
(new Project($r->all()))->save();
作者:
$project = Project::create($r->all());
更改退货:
return redirect('/projects')->with('store','');
作者:
return redirect('/projects')->with(['project' => $project]);
要检索项目的创建者时,请执行以下操作:
<tr>
<th>Created by: {{ $project->creator->name }}</th>
</tr>