Laravel Post Request - php

I have a table called Customer and with a Get Request I can already get all the Data (which I created with phpMyAdmin) on a HTML Template.
Now I want to create a new Customer with a Post Request.
This is the way I thought it would work:
In the Controller:
public function addNewCustomer(Request $request)
{
return \app\model\Customer::create($request->all());
}
The route:
Route::post('posttest', 'CustomerController#addNewCustomer');
How can I create a validation for it?

You can add validation of form like below in addNewCustomer,
public function addNewCustomer(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|max:255',
'body' => 'required',
]);
return \app\model\Customer::create($request->all());
}
For more information about input validation in Laravel Please readout Laravel Validation Documentation

Related

How to deal with similar validation rules in Laravel?

I have not so much practical experience with Laravel yet and I wondered what is the best way to deal with similar validation logic and where to put it.
Let's say I have an API resource Controller for Products with a store and an update method like so:
public function store(Request $request)
{
$request->validate([
'name' => 'required|string|max:100',
'description' => 'nullable|string|max:1000',
'price' =>'required|decimal:0,2|lt:1000'
]);
return Product::create($request->all());
}
public function update(Request $request, Product $product)
{
$request->validate([
'name' => 'string|max:100',
'description' => 'nullable|string|max:1000',
'price' =>'decimal:0,2|lt:1000'
]);
return Product::update($request->all());
}
The only difference between the validation in store and update is that store adds the 'required' rule for 'name' and 'price'. My question is, if I can encapsulate both validations in one Form Request, or how can I avoid code duplication without adding unnecessary code?
With my understanding of Form Requests I would probably create two Form Request classes, StoreProductRequest and UpdateProductRequest, and maybe another helper class that defines the core validation rules. Then each Form request could call for example ProductHelper::getBaseValidationRules() and merge that with their extra requirements. Somehow I find that a bit overkill.
you can create a request for your validations and use them in your controllers
for example
php artisan make:request YOUR_REQUEST_NAME
then inside your request you can add your validations like this
public function rules()
{
return [
'name' => 'required|string|max:100',
'description' => 'nullable|string|max:1000',
'price' => 'required|decimal:0,2|lt:1000'
];
}
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
and in your method you can call it like this
public function update(YOUR_REQUEST_NAME $request, Product $product)
{
return Product::update($request->all());
}
for more information you can read this
https://laravel.com/docs/5.0/validation#form-request-validation
in case you want condition in the rules please check this video
https://www.youtube.com/watch?v=epMaClBOlw0&ab_channel=CodeWithDary
Okay based on the suggestions, I came up with the following solution:
I created a Form Request named ProductRequest and implemented the rules method as follows:
public function rules()
{
$rules = [
'name' => ['string', 'max:100'],
'description' => ['nullable', 'string', 'max:1000'],
'price' => ['decimal:0,2', 'lt:1000'],
];
// If the user wants to create a new Instance some fields are mandatory.
if ($this->method() === 'POST') {
$rules['name'][] = 'required';
$rules['price'][] = 'required';
}
return $rules;
}
This is fine for me. Although in a bigger project I probably would create two Form Requests, StoreProductRequest and UpdateProductRequest. They would share and update a base set of rules as I described in the question.

How to redirect to my new post when I created a new post | Laravel

I want to redirect to my new post when I created a new post in Laravel
But I get a ArgumentCountError
Too few arguments to function App\Http\Controllers\ArticlesController::store(), 1 passed in C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54 and exactly 2 expected
How can I fix it? Thanks
web.php
<?php
Route::resource('articles', ArticlesController::class);
Route::get('/', [ArticlesController::class, 'index'])->name('root');
Route::resource('articles.comments', CommentsController::class);
ArticlesController.php
public function store(Request $request, $id) {
$content = $request->validate([
'title' => 'required|max:30',
'content' => 'required|min:10'
]);
//限制只有透過登入才能CREATE文章
auth()->user()->articles()->create($content);
return redirect('articles/'. $id)->with('notice', '文章發表成功!');
}
create.blade.php
<form class="container-fluid" action="{{ route('articles.store') }}" method="post">
Check your store() method. I think it should get only Request $request.
Example
public function store(Request $request) {
$content = $request->validate([
'title' => 'required|max:30',
'content' => 'required|min:10'
]);
//限制只有透過登入才能CREATE文章
$article = Article::create($content); // static is not best practice, only for example
return redirect('articles/'. $article->id)->with('notice', '文章發表成功!');
}
But before using the create method, you will need to specify either a fillable or guarded. Check docs
Presumably you need / have a way of viewing an article anyway, whether it's just been added or not, so in your web.php you would want a GET request to retrieve an article by passing its ID:
Route::get('/article/{id}', [ArticleController::class, 'viewArticle'])-> name('article.view');
Then you would want a POST request to add a new article :
Route::post('/addarticle', [ArticleController::class, 'addArticle'])-> name('article.add');
In your ArticleController, at the end of your addArticle method, once your new article has been created, you can then return a redirect to your "view article" route referencing its name, and passing in the parameter that it expects - the new article's ID - as part of the route, like so :
$article = new Article();
... populate the article's details here ...
return redirect()->route('article.view', ['id' => $article->id]);
I already solved it by my way
remove $id from store() function
just add $article before auth()->user()->articles()->create($content)
$id change to $article->id from redirect()
Example
public function store(Request $request) {
$content = $request->validate([
'title' => 'required|max:30',
'content' => 'required|min:10'
]);
$article = auth()->user()->articles()->create($content);
return redirect('articles/'. $article->id)->with('notice', '文章發表成功!');
}
Thank you

The smart way of set custom validations message in laravel without making a request class

I found difficulties to set custom validation message without making a
request class. That's why I am explaining it for a better
understanding.
Default validation of laravel:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|unique:categories',
]);
$input = $request->all();
Category::create($input);
Session::flash('create_category','Category created successfully');
return redirect('admin/categories');
}
It will show the default message of laravel. In this question-answer section I will show how easily I solved this problem with the help of laravel documentation.
you can find other ways of doing this here in laravel documentation.
You have to simply pass the three values to the validate parameter.
Your input as $request
Your rules as $rules
Your custom message as $message
public function store(Request $request)
{
$rules = ['name'=>'required|unique:categories'];
$message = [
'name.required' => 'The category name is required',
'name.unique' => 'Category name should be unique'
];
$this->validate($request, $rules, $message);
$input = $request->all();
Category::create($input);
Session::flash('create_category','Category created successfully');
return redirect('admin/categories');
}
I found that this is the smartest way of doing custom validation without making a request class. If your input field is a few and you want to your validation in the controller then you can do your validation in this way.
Thank's for reading.

Call form request from controller based on request input

I have a controller that accepts input. This input is parsed by a request validation (POSRequest). If the request validation succeeded, the request is then passed into the controller. Standard laravel stuff.I have to typehint in the controller POSRequest $requests in order to fire the request validation, how can I call other requests based on the input provided in POSRequest $request?Here is some code to clear things up a bit:public function process(POSRequest $request){ ... }All of my requests come to process function and based on input of $requests i need to call other functions:private function StartRequest(POSStartRequest $request) { ... }private function CheckRequest(POSCheckRequest $request) { ... }How can i call these frunctions from within the controller from within the process function and convert POSRequest to either one of other requests?Thank you in advance!
You can manually create validators in controller method
public function process(Request $request) {
$rulesFirstRequest = ['field1' => 'required', 'field2' => 'required'];
$rulesSecondRequest = ['field12' => 'required', 'field22' => 'required'];
$validator1 = Validator::make($request->all(), $rulesFirstRequest);
$validator2 = Validator::make($request->all(), $rulesSecondRequest);
if ($validator1->fails()) {
//do your stuff
if ($validator2->fails()) {
//do your stuff
}
}
// next stuff
}

Handle form submission Laravel 5

I just start learning Laravel 5, and I want to know what the proper way to handle submitted forms. I found many tutorials where we create two separate actions, where first render form, and the second actually handle form. I am came from Symfony2, where we create a single action for both, render and handle submitted form, so I want to know I need to create two separate actions because thats Laravel-way, or I can place all logic into single action, I do this like the folowing, but I dont like code what I get:
public function create(Request $request)
{
if (Input::get('title') !== null) {
$v = Validator::make($request->all(), [
'title' => 'required|unique:posts',
'content' => 'required',
]);
if ($v->fails()) {
return redirect()->back()->withErrors($v->errors());
}
$post = new Post(Input::all());
if ($post->save()) {
return redirect('posts');
}
}
return view('add_post');
}
So can somebody give me advice how I need do this properly? Thanks!
One of the most important reason to create two actions is to avoid duplicate form submissions . You can read more about Post/Redirect/Get pattern.
Another important reason is the way you keep the code cleaner. Take a look at this first change:
public function showForm(){
return view('add_post');
}
public function create(Request $request)
{
$v = Validator::make($request->all(), [
'title' => 'required|unique:posts',
'content' => 'required',
]);
if ($v->fails()) {
return redirect()->back()->withErrors($v->errors());
}
$post = new Post(Input::all());
if ($post->save()) {
return redirect('posts');
}
return redirect()->route('show_form')->withMessage();
}
The first thing that you can notice is that create() function is not rendering any view, it is used to manage the creation logic (as the name itself suggests). That is OK if you plan to stay in low-profile, but what happens when you do need to add some others validations or even better, re-utilize the code in other controllers. For example, your form is a help tool to publish a comment and you want to allow only "authors-ranked" users to comment. This consideration can be manage more easily separating the code in specific actions instead making an if-if-if-if spaghetti. Again...
public function showForm(){
return view('add_post');
}
public function create(PublishPostRequest $request)
{
$post = new Post($request->all());
$post->save()
return redirect('posts');
}
Take a look on how PublishPostRequest request takes place in the appropriated function. Finally, in order to get the best of Laravel 5 you could create a request class to keep all the code related with validation and authorization inside it:
class PublishPostRequest extends Request{
public function rules(){
return [
'title' => 'required|unique:posts',
'content' => 'required',
]
}
public function authorize(){
$allowedToPost = \Auth::user()->isAuthor();
// if the user is not an author he can't post
return $allowedToPost;
}
}
One nice thing about custom request class class is that once is injected in the controller via function parameter, it runs automatically, so you do not need to worry about $v->fails()

Categories