I am using laravel and vue for a project, I want to pass the user id to the table if the user is authenticated, but for some reason the authenticated user’s id is not passed to the query giving this error: SQLSTATE[HY000]: General error: 1364 Field ‘user_id’ doesn’t have a default value
This is laravel code for controller:
<?php
namespace AppHttpControllers;
use AppModelsSurveys; // Correct the model name
use AppHttpRequestsStoreSurveyRequest;
use AppHttpRequestsUpdateSurveyRequest;
use IlluminateHttpRequest;
use AppHttpResourcesSurveyResource;
class SurveyController extends Controller
{
public function index(Request $request)
{
$user = $request->user();
return SurveyResource::collection(Surveys::where('user_id', $user->id)->paginate());
}
public function store(StoreSurveyRequest $request)
{
$result = Surveys::create($request->validated());
return new SurveyResource($result);
}
}
This is the code for Request (StoreSurveyRequest):
<?php
namespace AppHttpRequests;
use AppModelsSurveys;
use IlluminateFoundationHttpFormRequest;
use IlluminateSupportStr;
use IlluminateValidationRule;
use IlluminateValidationRulesEnum;
class StoreSurveyRequest extends FormRequest
{
public function authorize()
{
return true;
}
protected function prepareForValidation()
{
$this->merge([
'user_id' => $this->user()->id
]);
}
public function rules()
{
return [
'title' => 'required|string|max:1000',
'image' => 'nullable|string',
'user_id' => 'exists:users,id',
'status' => 'required|boolean',
'description' => 'nullable|string',
'expire_date' => 'nullable|date|after:tomorrow',
'questions' => 'array',
];
}
}
2
Answers
use IlluminateSupportFacadesAuth;
please try with this method.
What are you currently trying to achieve? Do you want to get a user who is already logged in? If so, you can use