Laravel Put/Patch Request - php

Im trying to do a Put/Patch Request, I am using Postman, this is my current Code:
class CustomerController extends Controller
{
public function getAllCustomer()
{
return Customer::get();
}
public function addNewCustomer(Request $request)
{
$validatedData = $request->validate([
'Title' => 'required',
'Name' => 'required|max:255',
'Surname' => 'required|max:255',
'Email' => 'required',
'Phone' => 'required',
'Password' => 'required',
'dateofBirth' => 'required'
]);
return \app\model\Customer::create($request->all());
}
public function update (Request $request , Customer $id)
{
$id->update($request->all());
}
And this my route:
Route::put('Customer/{id}' , 'CustomerController#update');
Im trying to insert some Parameters into Postman, but I think the way I do it is not correct, right now I do it like this:
Im not getting any Errors, but nothing is happening, maybe somebody knows a solution.
I want to Change the Name of the customer.
Thanks!

Try to set x-www-form-urlencoded for body in postman.

Related

Laravel Update Function Don't Save New Data

So I have trouble updating data from edit form. I tried to use 'dd' and it's collect all the data it needs. No error, but the data on database not change.
public function update(Request $request, Stationery $stationery)
{
$validated = $request->validate([
'category_id' => 'required',
'nama' => 'required',
'satuan' => 'nullable',
'harga' => 'required',
'keterangan' => 'nullable'
]);
// dd($validated);
Stationery::where('id', $stationery->id)
->update($validated);
return redirect('/barang/pakaihabis')->with('success', 'Data Berhasil Diubah!!');
}
The success message pop out but the data still same.
The only protected in the model Stationery
protected $guarded = ['id'];
You can use:
$stationery->update($validated);
There is no need for where because you use route model binding ;)

How to stop auto login after registration in Laravel 8 breeze

Hi I am fairly new to Laravel framework. I am trying to create a separate controller replicating the registeredusercontroller.php in laravel breeze to have a function for admin user to be able to add new users. But I am having trouble with auto login and as soon as I add a new user it automatically logs in to the new user. How can I stop this from happening. I saw posts stating to remove
$this->guard()->login($user);
but when I see the app/Auth/registeredusercontroller.php I don't see that line.
public function store(Request $request)
{
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|confirmed|min:8',
]);
Auth::login($user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]));
$user->attachRole('user');
event(new Registered($user));
return redirect(RouteServiceProvider::HOME);
}
how can I stop the auto login after registration.
Any help is greatly appreciated.
You can do this proper way like using custom request handler.
The parameter you need is name, email, password.
So add CreateUserRequest above app/http/request
<?php
namespace App\Http\Requests;
use Illuminate\Http\Request;
class CreateUserRequest extends Request
{
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|confirmed|min:8',
];
}
}
And into your controller just do this;
public function store(CreateUserRequest $request) // add your custom request as a parameter
$user = User::create($request)
These codes makes your code structure clear and clean.

POST calls return 404 In Laravel

I am creating signup Api 1st call is GET and 2nd is POST call.
When I make GET[POSTMAN] call I get proper response from the controller but when I make POST it returns 404.
web.php
// sign up api
Route::get('signup','Api\RegistrationController#createUser');
Route::post('/signup','Api\RegistrationController#storeUser');
RegistrationController.php
public function createUser(){
return "Get : Sign up";
}
public function storeUser() {
// validate the form
$this->validate(request(),[
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required',
'password' => 'required'
]);
// create and save the user
$user = Register::create(request(['firstname', 'lastename', 'email', 'password']));
return "Registration complete";
}
I am using laravel 5.4. When route url is kept same (i.e signup) then GET method executes for POST call, when route url different it returns 404.
Screenshot : its a POST call but GET route executed
Try this and let me know:
use Illuminate\Http\Request;
public function storeUser(Request $request) {
// validate the form
$this->validate($request,[
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required',
'password' => 'required'
]);
// create and save the user
$user = Register::create($request->all());
return "Registration complete";
}
Note: When developing api's always define Api routes in api.php file.
Write All your API Routes in api.php file instead of web.php
use Illuminate\Http\Request;
public function storeUser(Request $request) {
// first check whether your request is coming here or not
// if not coming
// it is the issue of Routing
dd('coming..');
//if it prints coming then comment this dd
$this->validate($request,[
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required',
'password' => 'required'
]);
$user = Register::create($request->all());
}
For api requests , you should not use a custom Http Request that Extends FormRequest but instead
use Illuminate\Http\Request;

How do I get ONLY the validated data from a laravel FormRequest?

Lets say I have the following Custom Request:
class PlanRequest extends FormRequest
{
// ...
public function rules()
{
return
[
'name' => 'required|string|min:3|max:191',
'monthly_fee' => 'required|numeric|min:0',
'transaction_fee' => 'required|numeric|min:0',
'processing_fee' => 'required|numeric|min:0|max:100',
'annual_fee' => 'required|numeric|min:0',
'setup_fee' => 'required|numeric|min:0',
'organization_id' => 'exists:organizations,id',
];
}
}
When I access it from the controller, if I do $request->all(), it gives me ALL the data, including extra garbage data that isn't meant to be passed.
public function store(PlanRequest $request)
{
dd($request->all());
// This returns
[
'name' => 'value',
'monthly_fee' => '1.23',
'transaction_fee' => '1.23',
'processing_fee' => '1.23',
'annual_fee' => '1.23',
'setup_fee' => '1.23',
'organization_id' => null,
'foo' => 'bar', // This is not supposed to show up
];
}
How do I get ONLY the validated data without manually doing $request->only('name','monthly_fee', etc...)?
$request->validated() will return only the validated data.
Example:
public function store(Request $request)
{
$request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
$validatedData = $request->validated();
}
Alternate Solution:
$request->validate([rules...]) returns the only validated data if the validation passes.
Example:
public function store(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
}
OK... After I spent the time to type this question out, I figured I'd check the laravel "API" documentation: https://laravel.com/api/5.5/Illuminate/Foundation/Http/FormRequest.html
Looks like I can use $request->validated(). Wish they would say this in the Validation documentation. It makes my controller actions look pretty slick:
public function store(PlanRequest $request)
{
return response()->json(['plan' => Plan::create($request->validated())]);
}
This may be an old thread and some people might have used the Validator class instead of using the validator() helper function for request.
To those who fell under the latter category, you can use the validated() function to retrieve the array of validated values from request.
$validator = Validator::make($req->all(), [
// VALIDATION RULES
], [
// VALIDATION MESSAGE
]);
dd($validator->validated());
This returns an array of all the values that passed the validation.
This only starts appearing in the docs since Laravel 5.6 but it might work up to Laravel 5.2

Laravel Validator Not Working Properly - Redirecting main page

Laravel 5.5
public function register(Request $request) {
request()->validate([
'email' => 'required:email'
'password' => 'required|min:6'
]);
return response()->json(["message" => "Hello World"]);
}
If validator is fails, not giving error messages. Redirecting main page.
If the code you're using redirects you to the previous page when validation fails, it means that you didn't tell the server what kind of response you want to receive.
Set a proper header to get JSON. It will make the validator send JSON in response. For example:
$.ajax({
headers: {
Accept : "application/json"
},
...
});
Then this code will work as expected:
public function register(Request $request)
{
$request->validate([
'email' => 'required:email'
'password' => 'required|min:6'
]);
return response()->json(["message" => "Hello World"]);
}
I had the same problem when testing my rest api in Postman application.
if we don't want to modify our current code of laravel redirect repose, we have to put Accept:-application/json and ContentType:-application/json
For modifying code in controller class file, i did it like this and got the json response instead of redirecting to home page.
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6',
]);
if ($validator->fails()) {
return response()->json($validator->errors());
} else {
// do something
}
}
before it looks like below codes it was redirecting to home page
This is validator function
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6',
]);
}
public function register(Request $request)
{
// Here the request is validated. The validator method is located
// inside the RegisterController, and makes sure the name, email
// password and password_confirmation fields are required.
$this->validator($request->all())->validate();
// A Registered event is created and will trigger any relevant
// observers, such as sending a confirmation email or any
// code that needs to be run as soon as the user is created.
event(new Registered($user = $this->create($request->all())));
// After the user is created, he's logged in.
$this->guard()->login($user);
// And finally this is the hook that we want. If there is no
// registered() method or it returns null, redirect him to
// some other URL. In our case, we just need to implement
// that method to return the correct response.
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
You can do this like this :
$validator = Validator::make($request->all(), [
'email' => 'required|email', //use pipe here to apply multiple validations rules and add a ','
'password' => 'required|min:6'
]);
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()]);
}
return response()->json(["message" => "Hello World"]);
The validation is working well, but, $request->validate() will redirect you to the previous page. I recommend you to manually create your validations:
Manually Creating Validations.
You could do something like this:
use Illuminate\Http\Request;
use Validator;
class YourClass extends Controller{
public function yourFunction(Request $request) {
$validator = Validator::make($request->all(),[
'field_1' => 'rule1|rule2',
'field_2' => 'rule1|rule2'
]);
if ($validator->fails()) {
return response()->json($validator->errors());
} else {
/*Something else*/
}
}
}
try this, hope this code can help you
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);

Categories