当我收到错误ErrorException(E_NOTICE)时,我试图使用laravel在mysql中写入数据 尝试获取非对象的属性,我不知道该在哪里出现问题,请帮助我。
我的控制器代码是PublicationController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\publication;
use Auth;
class PublicationController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
return view('publications');
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
publications::create([
'user_id' => Auth::user()->id,
'title' => request('title'),
'status' => request('status'),
'year' => request('research_area')
]);
return 'inserted';
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
为模型代码提供了publication.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class publication extends Model
{
//
protected $fillable = ['title','status','year'];
}
给出了我的路线代码。
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
Route::get('education', 'EducationController@index');
Route::post('edu', 'EducationController@store');
Route::get('publications','PublicationController@index');
Route::post('pub','PublicationController@store');
错误被赋予类ErrorException(E_NOTICE) 尝试获取非对象的属性,如果有人知道问题出在哪里,请提供帮助
答案 0 :(得分:1)
考虑将PublicationController
放在身份验证中间件后面:
class PublicationController extends Controller
{
...
public function __construct()
{
$this->middleware('auth');
}
...
}
您还可以使用路由组:
Route::middleware(['auth'])->group(function () {
// your routes
});
如果Auth::user()
为空,那么Auth::user()->id
会给您提到的异常。将路由或控制器放在中间件后面应该可以解决此问题。
修改
这假设您正在使用Laravel 5.6 https://laravel.com/docs/5.6。这应该适用于5.5和5.7。
答案 1 :(得分:0)
最后,我仅在模型可填充的arry中包含“ user_id”,就找到了问题的答案,并且以上代码正常工作。