Laravel 6 how to store logged user's id in controller - laravel

I am trying to store logged user's id but I am getting this error
ErrorException
array_map(): Argument #2 should be an array
This is the code in the controller
public function store(Request $request)
{
if (!auth()->check()) {
abort(403, 'Only authenticated users can create new posts.');
}
$data = request()->validate([
'id' => $id = Auth::id(),
'content' => 'required',
'topic' => 'required',
'hashtag' => 'required'
]);
$check = Tweets::create($data);
return Redirect::to("form")->withSuccess('Great! Form successfully submit with validation.');
}
The error is in this line of code.
'id' => $id = Auth::id(),
I know that should be a string but to explain to you what I am trying to do, and I still have not found any solution.

Do it Like this.
public function store(Request $request)
{
if (!auth()->check()) {
abort(403, 'Only authenticated users can create new posts.');
}
$request->validate([
'content' => 'required',
'topic' => 'required',
'hashtag' => 'required'
]);
$data = $request->all();
$data['id'] = Auth::id();
$check = Tweets::create($data);
return Redirect::to("form")->withSuccess('Great! Form successfully submit with validation.');
}

Delete this
'id' => $id = Auth::id(),
and add
$data['id'] = Auth::id();
before
$check = Tweets::create($data);
That should work

Related

how can I save user ID on Laravel

Hello I am newbie.
// Framework 6.9.0
$id = id(); // user id
public function store(Request $request) {
$data = $request->validate([
'title' => 'required|max:100',
'description' => 'required',
'user_id' => $id
]);
CRUD::create($data);
return redirect('/')->with('success', 'test is successfully saved');
}
'user_id' => $id Is it possible ? how can I insert a "user id" in TABLE
I will be waiting for your response !
If you are using the default authentication system, you can use the Auth facade.
'user_id' => Auth::id()
and add this line at the top of your controller:
use Illuminate\Support\Facades\Auth;
Also, remove this line:
$id = id();

Validation error in api response in laravel 5.6

I want to store data through api. It's working but problem is when I add validation it does not give me corresponding message . How can I fix it? Thanks in advance
Here is my route
Route::post('api/add_user', 'TestApiController#store');
Here is my controller
public function store(Request $request)
{
$validation = Validator::make(Request::all(), [
'name' => 'required',
'phone' => 'required',
'email' => 'required'
]);
if ($validation->errors()) {
return $errors->toJson();
} else {
$testApi = new testApi();
$testApi->name = $request->name;
$testApi->phone = $request->phone;
$testApi->email = $request->email;
$testApi->save();
return "ok";
}
}
to handle that your method should be like this :
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'phone' => 'required',
'email2' => 'required|email'
]);
if($validator->fails()){
// here we return all the errors message
return response()->json(['errors' => $validator->errors()], 422);
}
$testApi = new testApi();
$testApi->name = $request->name;
$testApi->phone = $request->phone;
$testApi->email = $request->email;
$testApi->save();
// 201 http code means that the server has proceced your request correctly
return response()->json([], 201);
}
You don't have to manually do this. simply
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'phone' => 'required',
'email' => 'required'
]);
$testApi = new testApi();
$testApi->name = $request->name;
$testApi->phone = $request->phone;
$testApi->email = $request->email;
$testApi->save();
return "ok";
}
this will automatically handles validation and returns error message when invalid.
Update
if you wanna stick with your approach. this is where you need to change.
if ($validation->fails()) {
return $validation->errors();
}

How to store data after confirm screen page

This is contact form. I would like to recive email and save this data to my mysql. I use Laravel. Email function works good. but There is a problem. I would like to store all data at "function complete".
I validate all data at "function confirm" This is confirm screen page so user still not submit yet. I tried to write code like this at "function complete" but error say "Undefined variable: request" Could you teach me how to fix my code please?
public function confirm(Request $request)
{
$rules = [
'title' => 'required',
'search' => 'required',
'amount' => 'required|integer',
'email' => 'required|email',
'body' => 'required',
];
$this->validate($request, $rules);
$data = $request->all();
$request->session()->put($data);
return view('mail.confirm', compact("data"));
}
public function complete()
{
$data = $request->all(); # 3)
$request->session()->put($data); # 4)
Contact::create($request->all());
   
$data = session()->all();
Mail::send([ ・・・
You have to pass the parameter type $request as you did in confirm function.In your complete function, you don't declare $request variable and accessing it without declaration
public function confirm(Request $request)
{
$rules = [
'title' => 'required',
'search' => 'required',
'amount' => 'required|integer',
'email' => 'required|email',
'body' => 'required',
];
$this->validate($request, $rules);
$data = $request->all();
// setting session key value for you data
$request->session()->put('data',$data);
return view('mail.confirm', compact("data"));
}
/*
* complete page
*/
public function complete(Request $request)
{
// after confirm button click get data from session with key '#data' ;
$data = $request->session()->pull('data');
// get token value in variable and remove from data set so we can use mass assignement
$token = array_shift($data);
// creating record
$Contact = Contact::create($data);
Mail::send(['text' => 'mail.temp'], $data, function($message) use($data){
$message->to($data["email"])->bcc('lara_admin#sakura.ne.jp')->from('1110.ne.jp')->subject('thnak you。');});
Mail::send(['text' => 'mail.admintemp'], $data, function($message) use($data){
$message->to('lara_admin#sakura.ne.jp')->from('emailconf#.ne.jp')->subject('you got order');});
$data = session()->regenerateToken();
return view('mail.complete');
}

How can i update my form with validation in laravel?

My form validation is not working in Laravel. How can I update my form with validation in Laravel?
You can check my code here-
public function update(Request $request, $id)
{
$id->validate([
'Name'=>'required',
'UserName'=>'required',
'Password'=>'required|min:6',
'email'=>'required|email',
]);
$updateInfo= Info::findOrFail($id);
$updateInfo->user_id = $request->input('user_id');
$updateInfo->Name = $request->input('Name');
$updateInfo->UserName = $request->input('UserName');
$updateInfo->Password = $request->input('Password');
$updateInfo->save();
return redirect('/info');
}
You need to call validate on $request, like this-
$request->validate([
'Name'=>'required',
'UserName'=>'required',
'Password'=>'required|min:6',
'email'=>'required|email',
]);
Here is the full code-
public function update(Request $request, $id)
{
$request->validate([
'Name'=>'required',
'UserName'=>'required',
'Password'=>'required|min:6',
'email'=>'required|email',
]);
if (!$validator->fails()) {
$updateInfo= Info::findOrFail($id);
$updateInfo->user_id = $request->input('user_id');
$updateInfo->Name = $request->input('Name');
$updateInfo->UserName = $request->input('UserName');
$updateInfo->Password = $request->input('Password');
$updateInfo->save();
} else {
\Session::flash('error', $validator->messages()->first());
return redirect()->back()->withInput();
}
return redirect('/info');
}
I have added one more condition in the code to handle the validation errors. If validation fails then it will redirect back with your inputs as well as the validation error messages. Make sure you have error session flash in your blade views to show the errors.
For me this is best way , i can keep on track on query and other exceptions by putting it in try catch block
public function update(Request $request, $id)
{
try{
$validator = Validator::make($request->all(), [
'name' => 'required',
'UserName' => 'required',
'Password' => 'required',
'email' => 'required|email',
]);
if($validator->fails()) {
return redirect()
->route('path_to_edit_form')
->withErrors($validator)
->withInput();
}
Info::where('id',$id)->update([
'user_id' => $request->get('user_id'),
'Name' => $request->get('Name'),
'UserName' => $request->get('UserName'),
'Password' => $request->get('Password'),
]);
return back()->with([
'alert_type' => 'success',
'message' => 'User info updated successfully.'
]);
}catch(\Exception $e){
return back()->with([
'alert_type' => 'danger',
'message' => $e->getMessage()
]);
}
}

Lumen: update records via json body

I have a Laravel Lumen API. I'm seeing an issue with the update functionality.
In my controller, the code for updating an item is:
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'completed' => 'required',
]);
$todo = Todo::find($id);
$todo->name = $request->name;
$todo->description = $request->description;
$todo->completed = $request->completed;
$todo->save();
return response()->json(['status' => 'success']);
}
I can update the todo item using:
http://lumen-todo.app/api/51?name=test&description=test&completed=1
however was hoping I could send the parameters in a json body, like this
PUT http://lumen-todo.app/api
{
"id": 1
"name": "Test",
"description": "Test",
"completed": 1,
}
For adding items, it works via a json body, so don't understand why it does not work for updates. For info, the 'add item' controller code is here:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'completed' => 'required'
]);
$todo = new Todo();
$todo->name = $request->name;
$todo->description = $request->description;
$todo->completed = $request->completed;
$todo->save();
return response()->json(['status' => 'success']);
}
If you want to get the json data from request payload, validate and store it, use
public function store(Request $request)
{
$data = $request->json()->all();
$this->validate($data, [
'name' => 'required',
'description' => 'required',
'completed' => 'required'
]);
$resource = $this->model->find($id);
$resource->fill($request);
$resource->save();
return response()->json(['status' => 'success']);
}
Instead of doing this:
$todo = new Todo();
$todo->name = $request->name;
$todo->description = $request->description;
$todo->completed = $request->completed;
$todo->save();
Do, this:
use App\Todo;
protected $model;
public function __construct(Todo $model) {
$this->model = $model;
}
$resource = $this->model->find($id);
$resource->fill($request);
$resource->save();
Also, you can do json_decode() function to change your json params to array and use that to validate and save data.

Resources