Put method not working to pass parameter in laraverl - laravel

My route
Route::put('/users/{$id}', 'ApiController#profileUpdate')->name('user.update');
//profile update function
public function profileUpdate(Request $request){
try{
$validator = $this->validatorProfile($request->all());
if ($validator->fails()) {
$messages = $validator->messages();
return response()->json([
'status' => 400,
'error' => true,
'result' => false ,
'message'=> $messages,
'data' => []
]);
}
$id = $request->id;
$token = $request->header('authorization');
$user_id = JWTAuth::toUser($token)->id;
$user = User::find($user_id);
$data = $request->only('location','state','country','name');
$result = $user->profiles()->where(['user_id' => $$id])->update([
'location' => $data['location'],
'state' => $data['state'],
'country' => $data['country'],
]);
$result1 = $user->where(['id' => $user_id])->update([
'name' => $data['name'],
]);
return response()->json([
'status' => 200,
'error' => false,
'result' => true,
'message'=> "profile updated",
'data' => $data
]);
}
catch(Exception $e){
return response()->json([
'status' => 400,
'error' => true,
'result' => false,
'message'=> $e,
'data' => []
]);
dd($e);
}
}
Help me to find my mistake.
My url
http://localhost/project/public/api/v1/users/1
When i hit it on postman it give 404 error.

You will have to adjust your route parameter choice of naming. {$id} isn't going to work, but {id} will work just fine. Also the $$id reference in the code probably should be just $id.
As Alexey Mezenin has pointed out, it additionally would be good to add the $id parameter to your controller method to accept the route parameter.
Side Note:
When you are calling $request->id you are probably trying to get the route parameter, but that may not always return that. If there is any input in the Request named id that will be returned before a route parameter named id. It only tries to return a route parameter as a fallback.
$request->input('id') explicitly ask for an input named id.
$request->route('id') explicitly ask for a route parameter named id.
$request->id could be an input named id or a route parameter named id.

Since you're trying to pass ID, you need to add it as an argument. So, change this:
public function profileUpdate(Request $request)
To:
public function profileUpdate(Request $request, $id)

Related

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

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

laravel 8 API : how pass username with Auth as user_id value for store post

I'm building an API with Laravel 8.
I have a posts table with these columns:
id
category_id
user_id
title
body
picture
study_time
likes
tags
When a user is logged in as an author or admin, they can add a new post.
and for user_id field, I want to make that field guarded, I want to show username with JWTAuth::user()->username and register it for user_id column .. so no one can enter any value for it
edit :
when i send request it gives me this error : SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into posts
this is my store method in PostController:
$data = $request->all();
$validator = Validator::make($data, [
'category_id' => 'required',
'title' => 'required|max:100|unique:categories',
'body' => 'required',
'picture' => 'required',
'study_time' => 'required',
'tags' => 'null|string',
]);
if ($validator->fails()) {
return response(['error' => $validator->errors(), 'Validation Error']);
}
$tags = explode(",", $request->tags);
$post = Post::create($data);
$post->tag($tags);
return response()->json([
'username' => JWTAuth::user()->username,
'post' => $post
], 201);
add this after $data=$request->all():
$data['user_id'] = JWTAuth::user()->id;
or you can use this instead (if you define posts in user model):
JWTAuth::user()->posts()->create($data);
You can use $request->user() to get the current user.
$post = Post::create($data);
$post->tag($tags);
$post->username => JWTAuth::user()->username
return response()->json([
'post' => $post
], 201);

Laravel: how to use validator for single elements?

I'm trying to make validation of $id and $offer_id inside my function:
public function getMessagesForOffer($id, $offer_id)
{
$validator = Validator::make($request->all(), [
'id' => 'required|numeric',
'offer_id' => 'required|numeric',
]);
if ($validator->fails()) {
return response([
'status' => 'error',
'error' => 'invalid.credentials',
'message' => 'Invalid credentials'
], 400);
}
}
This is throwing an error: "message": "Undefined variable: request",
And I see that it's incorrect coded, how can I correct it to work with single elements when there is no request inside my function?
$request->all() would just return array, so you can also use array here, so instead of $request->all() you can use:
['id' => $id, 'offer_id' => $offer_id]
or shorter:
compact('id', 'offer_id')

Manually Passing a Foreign key Value

I can not pass a foreign key value (which is user_id) to my newly created article.
Here is my code...
<?php
if (is_null($request->user_id)) {
$request->user_id = $user->user_id;
}
$request->validate(['title' => 'Required|string|min:3', 'body' => 'Required|string|min:5', 'user_id' => 'Required|exists:users,user_id']);
if ($article = Article::create($request->all())) {
event(new ArticleCreated($user));
return response()->json(['success' => true, 'reason' => 'Article Created successfully', $article]);
} else {
return 'Article could not be created';
}
Change this:
if($article = Article::create($request->all())) {
$article->user_id = $request->user_id;
$article->save();
event(new ArticleCreated($user));
return response()->json(['success' => true, 'reason' => 'Article Created successfully', $article]);
}
Try this,
public function store(Request $request)
{
$request->validate([
'title' => 'Required|string|min:3',
'body' => 'Required|string|min:5',
]);
$data = $request->all();
//you don't need to validate user_id is correct
//if you are using auth middleware in the route
$user = auth()->user()
$data['user_id] = $user->id
if ($article = Article::create($data)) {
event(new ArticleCreated($user));
return response()->json([
'success' => true,
'reason' => 'Article Created successfully',
$article
]);
} else {
return 'Article could not be created';
}
}
Hope this helps
Check your fillable array in Article model, there must be user_id, and check if the user id is passed in the $request->all().

Validate route parameters in controller

I have a method like this in my UserController:
public function verifyUsername()
{
$rules = array(
'username' => 'required|max:30|unique:users,username'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return Response::json(array(
'success' => 'false',
'errors' => $validator->messages()
), 400);
}
else
{
return Response::json(array(
'success' => 'true'
));
}
}
I want to have a URL route like this:
/users/verify/username/{username}
How can I pass the username variable from the route to the method in the controller?
You pass in a array with uses set to the ControllerName#methodName
You might want to look at Named Routes for more information.
routes.php
Route::get('users/verify/username/{username}',
array('uses' => 'UserController#verifyUsername'));
Controller
public function verifyUsername($username)
{
//it would be nice if this works, but I don't think it will
$validator = Validator::make(Input::get('username'), $rules);
// something like this should work
$data = ['username' => $username];
$validator = Validator::make($data, $rules);
}

Resources