我正在使用laravel 5.2,我正在为我的应用程序开发一个消息传递系统。我正在尝试向数据库发送消息,但我不断收到此错误“调用未定义的方法Illuminate \ Database \ Query \ Builder :: messages()” 我的MessageController如下:
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use App\Http\Requests;
use App\Message;
class MessageController extends Controller
{
public function CreateMessage(Request $request)
{
$meso = new Message();
$meso->body = $request['body'];
$meso->subject = $request['subject'];
$request->user()->messages()->save($meso) ;
return redirect()->route('mail');
}
}
这是我的路线文件
Route::post('send', 'MessageController@CreateMessage');
这是我的表格:
<form role="form" class="form-horizontal" method="POST" action="{{ url('/send') }}">
<div class="form-group">
<label class="col-lg-2 control-label">To</label>
<div class="col-lg-10">
<input type="text" placeholder="" id="inputEmail1" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Cc / Bcc</label>
<div class="col-lg-10">
<input type="text" placeholder="" id="cc" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Subject</label>
<div class="col-lg-10">
<input type="text" placeholder="" id="inputPassword1" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Message</label>
<div class="col-lg-10">
<textarea rows="10" cols="30" class="form-control" id="" name=""></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<span class="btn green fileinput-button">
<i class="fa fa-plus fa fa-white"></i>
<span>Attachment</span>
<input type="file" name="files[]" multiple="">
</span>
<button class="btn btn-send" type="submit">Send</button>
<input type="hidden" value="{{ Session::token() }}" name="_token">
</div>
</div>
</form>
有人帮我调试此错误
答案 0 :(得分:0)
您应该在messages()
模型中创建User
关系:
public function messages()
{
return $this->hasMany('App\Message');
}
此外,您需要在user_id
表格中设置messages
foreign key defined才能使关系有效。
答案 1 :(得分:0)
试试这个:
$request->user()->messages->save($meso);
而不是:
$request->user()->messages()->save($meso);