将数据保存到数据库

saving data to the database

我正在尝试将数据保存到数据库,但遇到错误正在从空值创建默认对象

namespace App\Http\Controllers;

use Illuminate\Http\Request; use App\Message;

class MessageController extends Controller 
{ 
    public function submit(Request $request)
    { 
        $this->validate($request, [ 'name' => 'required', 'email' => 'required']);

        //create a new message
        $messge= new Message;

        $message->name=$request->name;
        $message->email = $request->email;
        $message->message = $request->message;

        //message save

        $message -> save();
        return redirect('/');
    }
}

您遇到的是"typo"。您正在使用变量 $messge 初始化模型,然后使用不同的名称 $message 访问它。正确代码:

namespace App\Http\Controllers;

use Illuminate\Http\Request; 

use App\Message;

class MessageController extends Controller 
{ 
    public function submit(Request $request)
    { 
        $this->validate(
            $request, 
            [ 
                'name' => 'required',
                'email' => 'required'
            ]
        );

        //create a new message
        $message= new Message;

        $message->name=$request->name;
        $message->email = $request->email;
        $message->message = $request->message;

        //message save
        $message->save();
        return redirect('/');
    }
}