【发布时间】:2019-10-11 00:50:24
【问题描述】:
我不明白我到底做错了什么。我正在尝试通过axios POST 请求将用户上传的文件的 URL 发送到我的数据库中,但我收到 500 错误。
注意:我使用 React.js 作为前端。
根据我的网络调用中的错误(它在 Laravl 日志中显示相同的错误),PostPicturesController 是问题所在,但我无法理解为什么 $postPictures 是罪魁祸首。
我做错了什么?
这里是PostPicturesController:
<?php
namespace App\Http\Controllers;
use App\User;
use App\PostPictures;
use Illuminate\Http\Request;
class PostPicturesController extends Controller
{
public function create(Request $request, PostPictures $postPicture) {
$uploadPic = $postPicture->user()->postPictures->create([
'body' => $request->body
]);
return response()->json($uploadPic->with('user')->find($uploadPic->id));
}
}
这里是User.php:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function postPictures() {
return $this->hasMany(PostPictures::class);
}
}
这是axios 电话:
submitImageAndRedirect() {
let picUrl = this.state.previewImgURL;
axios.post('/home', {
body: picUrl
}).then(response => {
// console
console.log(response);
// set state
this.setState({
pictures: [picUrl, response.data]
});
});
}
这是我在web.php的路线:
<?php
Auth::routes();
Route::group(['middleware' => ['auth']], function () {
Route::get('/', "HomeController@index")->name('home');
Route::get('/home', "HomeController@index")->name('home');
Route::post('/home', 'PostPicturesController@create')->name('home');
});
我的网络调用中的错误:
{message: "Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$postPictures",…}
exception: "ErrorException"
file: "/Users/name/workstation/website/app/Http/Controllers/PostPicturesController.php"
line: 12
message: "Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$postPictures"
【问题讨论】:
-
$postPicture->user()->postPictures到$postPicture->user->postPictures确保PostPictures应该与user相关。user相关postPictures -
您正在使用 API 调用,您需要通过
token来批准您的请求。 -
@Laravel 刚刚发布了我的 User.php 文件
标签: php reactjs laravel debugging axios