laravel-5.7: 数据未保存到数据库中,未找到对象

laravel-5.7: data is not saving into database, Object not found

我正在尝试将数据保存到数据库中,但它没有保存并说找不到该对象,任何人都可以建议我解决方案,我正在学习本教程:https://laracasts.com/series/laravel-from-scratch-2018/episodes/10

控制器:

public function index()
{
    $projects = Project::all();

    return view('projects.index', compact('projects'));
}

public function create()
{
    return view('projects.create');
}

public function store()
{
    $project = new Project();
    $project->title = request('title');
    $project->description = request('description');
    $project->save();

    return redirect('/projects');
}

路线:

Route::get('/projects','ProjectsController@index');
Route::post('/projects','ProjectsController@store');
Route::get('/projects/create','ProjectsController@create');

create.blade.php:

<form method="POST" action="/projects">
    {{ csrf_field() }}
    <div>
        <input type="text" name="title" placeholder="Project title">
    </div>
    <div>
        <textarea name="description" placeholder="Project description"></textarea>
    </div>
    <div>
        <button type="submit">Create Project</button>
    </div>
</form>

index.blade.php:

@foreach($projects as $project)
    <li>{{ $project->title }}</li>
@endforeach

您错过了在控制器存储中传递请求参数()

public function store(Request $request)
{
    $project = new Project();
    $project->title = $request->title;
    $project->description = $request->description;
    $project->save();
    return redirect('/projects');
}

并且不要忘记在控制器 class.

上方(外部)包含 use Illuminate\Http\Request;

您发布的 Laravel 代码在正确配置的网站下是正确的。您评论中的错误:

Object not found! The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error. If you think this is a server error, please contact the webmaster. Error 404 localhost Apache/2.4.33 (Win32) OpenSSL/1.1.0h PHP/7.2.7

Apache 错误页面,这意味着它根本没有从您的 laravel 项目中请求页面。数据可能保存在您的数据库中,但随后您重定向到项目之外的页面,Apache 找不到它。

您的网站位于 http://localhost/laravel/public,这意味着您需要访问位于 http://localhost/laravel/public/projects 的项目页面。然而,redirect('/projects') 给你一个 绝对 路径而不是 相对 路径,将你送到 http://localhost/projects,这不会存在。

解决方案

由于这是一个本地开发项目,我将跳过 Apache 配置不当的问题,并专注于其他避免错误的方法。

选项 1

使用 named route:

Route::get('/projects','ProjectsController@index')->name('projects.index');

并使用重定向的路由名称:

return redirect()->route('projects.index');

应该在您的项目中生成正确的 URL。

选项 2

使用 serve 进行开发而不是 Apache。

在您的 Laravel 项目目录中打开一个终端,然后 运行 这个命令:

php artisan serve

这将在 http://localhost:8000 启动 PHP 的内置网络服务器,完全跳过 Apache。在开发过程中,这完全没问题。