how to validate phone number and email address - laravel

i am new to laravel.. my problem is
i have a html form in which i am taking more than one phone number in a single input text tag using saprator ',' which is working fine.. but when i take that form data to controller i want to validate that each data should be a number and it should be of 10 digit only. same thing i want to do for the email also.
i have use laravel validation for the same but its not working... can anyone please help me on this.. thanx in advance: This is my controller store method code : Controller Code :
public function store(Request $request, Customer $newCustomer)
{
$mobileNo[] = explode(',',$request->contactNo);
$request->contactNo = $mobileNo;
$emails[] = explode(',',$request->email);
$request->email[] = $emails;
Validate::newCustomer($request);
}
Validation code :
public static function newCustomer(Request $request)
{
$request->validate([
'companyName' => 'required|string',
'city' => 'required|string',
'contactNo' => 'required|array',
'contactNo.*' => 'digits_between:10,10',
'email' => 'required|email',
'email.*' => 'email',
]);
}

Related

How to upload file in relationship hasOn<->belongsTo Laravel Backpack

Can be possible to store a file uploaded to a related table?
Scenario: I have a usres table in database and another one pictures. Users Model have the following function
public function picture()
{
return $this->hasOne(Picture::class);
}
And the Picture Model have the following function.
public function user_picture()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
Is possible to store the picture in pictures database table (id, user_id, img_path) from the UserCrudController store() function?
try something like this
public function store(Request $request)
{
Picture::create([
'user_id' => // get the user id from $request or auth()->user(),
'img_path' => $request->file('image')->store('images', 'public'),
]);
return // your view or something else
}
Let's say it is a registration form that need to insert an image. Instead of using the Picture model directly you can just do this :
public function store(Request $request)
{
$request->validate(...);
$user = User::create(...);
//It will ensure that the image belongs to the user.
$user->picture()->create([
'image_path' => $request->file('image')->store('images');
])
}
I resolved the issue with the following steps.
As per Laravel Backpack I added the input field in the Blade:
#include('crud::fields.upload', ['crud' => $crud, 'field' => ['name' => 'img1', 'label' => 'Image 1', 'type' => 'upload', 'upload'=> true, 'disk'=>'uploads', 'attributes' => ['id' => 'img1', 'capture' => 'user']]])
After this I added the function in the User Controller as follow:
$request->validate(['img1' => 'mimes:jpg,png,jpeg|max:5120']);
$fileModel = new Picture;
if($request->file()) {
$fileName1 = time().'_'.$request->img1->getClientOriginalName();
$filePath1 = $request->file('img1')->storeAs('uploads', $fileName1, 'public');
$fileModel->name = time().'_'.$request->img1->getClientOriginalName();
$fileModel->img1 = '/storage/' . $filePath1;
$fileModel->save();
}
With these lines of code I was able to store the related Picture with the User.
Thank you all for the guidelines.

Validating form comaring two fields values

I'm trying to find Laravel 8 documentation on how to validate comparing two fields to each other. I'm creating an app that allows creating matches from teams in a database table, using the create() method in the controller. I looked into Laravel #Validation, even #Custom Validation Rules, but I can't find anything when comparing the two fields.
public function store(Request $request)
{
$validatedData = $request->validate([
'local_team' => 'required',
'local_score' => 'required|numeric',
'visitor_team' => 'required',
'visitor_score' => 'required|numeric',
]);
$score = new Score();
$score->local_team = $request->local_team;
$score->local_score = $request->local_score;
$score->visitor_team = $request->visitor_team;
$score->visitor_score = $request->visitor_score;
$score->save();
$new = true;
return redirect()->route('scores.show',
['id' => $score->id, 'new' => true]);
}
In my case, the 'local_team' and 'visitor_team' fields should be different. Any clue on how to do it?

Laravel : sending data from one page to second to third to submit in DB

Need to send data from 1 -> 2 (Add more info) -> 3 (Preview & Submit).
First page user submit a url in an input
Second page user submit the url related information like Title, Description, Selects a category, add tags etc. All in inputs and textarea.
Third page for final view of submitted information so far and submit it into the DB.
But the sedon pae won't go to third page it gives POST error.
Controller
public function submitUrl(Request $request)
{
$validatedData = $request->validate([
'link' => 'required|unique:links|min:5|active_url',
]);
$categories = DB::table('categories')->get();
return view('submit2')->with('validatedData', $validatedData)->with('categories', $categories);
}
public function submitData(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|between:15,150',
'category' => 'required',
'description' => 'required|between:250,500',
'tags' => ['required'],
]);
$categories = DB::table('categories')->get();
return $validatedData;
return view('submit3')->with('validatedData', $validatedData)->with('categories', $categories);
}
public function saveData(Request $request)
{
}
Route
Route::get('/submit', 'SubmitLinks#index')->middleware('auth');
Route::post('/submit2', 'SubmitLinks#submitUrl')->middleware('auth');
Route::post('/submit3', 'SubmitLinks#submitData')->middleware('auth');
Your first route is defined as:
Route::get('/submit', 'SubmitLinks#index')->middleware('auth');
and I believe you are using it to save first step data via POST. So change its method to post then like so:
Route::post('/submit', 'SubmitLinks#index')->middleware('auth');

Need help about passing club_id in player controller

I'm making football blog and I want to make that i can create players, but i have problem with it because i get eroor "Call to a member function players() on null" i know where is problem but i dont know how to solve it, I have similar problem with comments and posts but i done it and now again same problem but it dont work
//PlayersController
public function store(Request $request)
{
$this->validate($request, [
'fname' => 'required',
'lname' => 'required',
'age' => 'required',
'country' => 'required',
'position' => 'required',
'image' => 'image|nullable|max:1999',
'text' => 'required'
]);
//create Player
$player = new Player;
$player->fname = $request->input('fname');
$player->lname = $request->input('lname');
$player->age = $request->input('age');
$player->country = $request->input('country');
$player->position = $request->input('position');
$player->image = $fileNameToStore;
$player->text = $request->input('text');
$club = Club::find($request->get('club_id')); //problem
$club->players()->save($player); //problem
}
//club model
public function players()
{
return $this->hasMany(Player::class);
}
//player model
public function club()
{
return $this->belongsTo(Club::class);
}
Sounds like $club is coming back null and that's why Laravel is giving an error when you try to use players() on it. Have you checked that $request->get('club_id') is giving you what you expect?
Also don't forget that your new $player doesn't fully exist yet in the database until you do $player->save(). Not sure if you can save it and also create its relationship to $club in one line. You could try saving it first, and then attaching it.

Laravel avoid duplicate entry from model

I'm building a Laravel API. I have a models called Reservations. I want to avoid that a user creates two reservations for the same product and time period.
I have the following:
$reservation = Reservation::firstOrCreate([
'listing_id' => $request->listing_id,
'user_id_from' => $request->user_id_from,
'start_date' => $request->start_date,
'end_date' => $request->end_date,
]);
Edit after comments:
I'm also using validation
$validator = Validator::make($request->all(), [
'listing_id' => 'required|exists:listings,id',
'user_id_from' => 'required|exists:users,id',
'start_date' => 'required|date_format:"Y-m-d"|after:today',
'end_date' => 'required|date_format:"Y-m-d"|after:start_date'
]);
if ($validator->fails()) {
return response()->json(['error' => 'Validation failed'], 403);
}
Validation is working properly.
End of Edit
In my model I have casted the start_date and end_date as dates.
class Reservation extends Model
{
protected $fillable = ['listing_id', 'start_date', 'end_date'];
protected $dates = [
'start_date',
'end_date'
];
....
....
Documentation says:
The firstOrCreate method will attempt to locate a database record
using the given column / value pairs
However I notice that I'm still able to insert entries with the same attributes.
Any idea what I'm doing wrong or suggestions to fix it?
Probably there's a better way than this, but you can create an static method on Reservation to do this, like:
public static function createWithRules($data) {
$exists = $this->where('product_id', $data['product_id'])->whereBetween(*date logic that i don't remember right now*)->first();
if(!$exists) {
* insert logic *
} else {
* product with date exists *
}
}
So you can call Reservation::createWithRules($data)
You can achieve this using Laravel's built in ValidateRequest class. The most simple use-case for this validation, is to call it directly in your store() method like this:
public function store(){
$this->validate($request, [
'listing_id' => 'required|unique,
'start_date' => 'required|unique,
//... and so on
], $this->messages);
$reservation = Reservation::firstOrCreate([
'listing_id' => $request->listing_id,
'user_id_from' => $request->user_id_from,
'start_date' => $request->start_date,
'end_date' => $request->end_date,
]);
}
With this, you're validating users $request with by saying that specified columns are required and that they need to be unique, in order for validation to pass.
In your controller, you can also create messages function to display error messages, if the condition isn't met.
private $messages = [
'listing_id.required' => 'Listing_id is required',
'title.unique' => 'Listing_id already exists',
//... and so on
];
You can also achieve this by creating a new custom validation class:
php artisan make:request StoreReservation
The generated class will be placed in the app/Http/Requests directory. Now, you can add a few validation rules to the rules method:
public function rules()
{
return [
'listing_id' => 'required|unique,
'start_date' => 'required|unique,
//... and so on
];
}
All you need to do now is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic:
public function store(StoreReservation $request)
{
// The incoming request is valid...
// Retrieve the validated input data...
$validated = $request->validated();
}
If you have any additional question about this, feel free to ask. Source: Laravel official documentation.

Resources