laravel validatetor in controller seems not working - laravel

The validate() function from my sales controller seems not working, I am comparing it to my other controller, it looks like it should work but it is not. it looks like the validate() is being bypassed. here's my controller
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
class SalesController extends Controller
{
public function store(Request $request)
{
$this->validate($request, [
'user_id' => 'required',
'status_id' => 'required',
'currency_id' => 'required',
'company_id' => 'required',
'invoice_no' => 'nullable',
'notes' => 'nullable',
'admin_notes' => 'nullable',
'due_date' => 'nullable',
'publish' => 'nullable',
'product_id' => 'required|min:1',
'product_code' => 'required|min:1',
'product_name' => 'required|min:1',
'quantity' => 'required'
]);
$sales = $request->only(
'user_id',
'status_id',
'currency_id',
'currency_rate',
'due_date',
'company_id',
'invoice_no',
'notes',
'admin_notes',
'delivery_date',
'publish'
);
$sales['grandtotal'] = (float) str_replace(',', '', $request->grandtotal);
$sales['grandtotalcost'] = (float) str_replace(',', '', $request->grandtotalcost);
$sales = Sales::create($sales);
$input = $request->all();
for($i=0; $i<= count($input['quantity']); $i++) {
if(empty($input['quantity'][$i]) || !is_numeric($input['quantity'][$i])) continue;
$items = [
'sales_id' => $sales->id,
'product_id' => $input['product_id'][$i],
'product_code' => $input['product_code'][$i],
'product_name' => $input['product_name'][$i],
'price' => $input['price'][$i],
'cost' => $input['cost'][$i],
'quantity' => intval($input['quantity'][$i]),
'total_price' => (float) str_replace(',', '', $input['total_price'][$i]),
'total_cost' => (float) str_replace(',', '', $input['total_cost'][$i]),
];
Salesitems::create($items);
}
// $ponumbers = Ponumbers::create($request->only('purchase_no'));
$invnum = $request->all();
$invnumbers = new Invnumbers;
$invnumbers->sales_num = $invnum['invoice_no'];
$invnumbers->save();
if ($request){
Session::flash('message','Invoice was successfully added');
Session::flash('m-class','alert-success');
} else {
Session::flash('message','Data is not saved');
Session::flash('m-class','alert-danger');
return redirect()->route('sales.index');
}
return redirect()->route('sales.index');
}
}
My Blade
<input class="form-control autocomplete_txt product_name" type='text' data-type="product_name" id='product_name_1' name='product_name[]' for="1" readonly/>
#if ($errors->has('product_name')) <p class="help-block">{{ $errors->first('product_name') }}</p> #endif
if I submit my form with product name, instead of throwing error from validate,

By seeing your code, to me it seems your product_id should be an array. So the validation should be:
'product_id' => 'array|required|min:1',
'product_id.*' => 'required',
instead of
'product_id' => 'required|min:1',

Try to use $request->validate([... instead of $this->validate($request, [.... I'm not sure is there validate in your controller...

Related

When use create() the fillable values come null

i have an array with values that i am trying to insert it in the database, but when i use create() the values are inserted as null in database while if i use insert() the values insert correct.
This is the code from the controller
public function store(Request $request)
{
$request->validate([
'order_number' => 'required',
'client' => 'required',
'products' => 'required',
'amount' => 'required',
'description' => 'required',
]);
for($i = 0; $i < count($request->products); $i++)
{
$values[] = [
'order_number' => $request->order_number,
'client' => $request->client,
'products' => $request->products[$i],
'amount' => $request->amount[$i],
'description' => $request->description
];
}
Order::create($values);
return redirect('/')->with('msg', 'Order Saved successfully!');
}
and this is the code from the model
public $timestamps = true;
protected $fillable = [
'order_number',
'client',
'products',
'amount',
'description',
];
The names are the same and in the database, any reason why the values come null when i use create() method?
insert() method accepts multiple objects in form of arrays to be created, for example :
DB::table('users')->insert([
['email' => 'picard#example.com', 'votes' => 0],
['email' => 'janeway#example.com', 'votes' => 0],
]);
But create() method does not accept such structure. You cannot create multiple entries using this method. So in this case you either keep using insert(), either move your create() inside for loop.
Edit : createMany() works only on relationships, and apparently DB manipulation in loops is antipattern. In that case you can do something like this :
$created_at = now();
for($i = 0; $i < count($request->products); $i++)
{
$values[] = [
'order_number' => $request->order_number,
'client' => $request->client,
'products' => $request->products[$i],
'amount' => $request->amount[$i],
'description' => $request->description,
'created_at' => $created_at,
'updated_at' => $created_at,
];
}
Order::insert($values);

Send Email with multiple images in Laravel9

I'm having problem that I would like to send Email with multiple images in Laravel9.
I wrote below code.
My goal is send Email with multiple images and
sametime each image file name stores into mysql's 'fileattach' column as photo1, photo2, photo3(one line)
Could someone correct my code please?
blade file
<div class="col-sm-6">
<input type="file" name="files[]" accept="file_extension|image/*|media_type" multiple>
</div>
Controller
public function saveContact(Request $request) {
$this->validate($request, [
'name' => 'required',
]);
if(count($files) > 0) {
foreach($files as $file) {
$message->attach($file->getRealPath(), array(
'as' => $file->getClientOriginalName(),custom name
'mime' => $file->getMimeType())
);
}
}
$contact = new Contact($request->all());
$contact->save();
\Mail::send('admin_email_tpl', //admin tpl
array(
'sno' => $request->get('sno'),
'name' => $request->get('name'),
'email' => $request->get('email'),
'files' => $request->post('files'),
), function($message) use ($request)
{
$message->from('123#123foobar.com');
$message->to('123#123foobar.com');
$message->subject('Thank You');
});
You are almost there, need to put the attachment code into callback method to mail.
public function saveContact(Request $request) {
$this->validate($request, [
'name' => 'required',
]);
//Get the $files array here
$files = [];
$contact = new Contact($request->all());
$contact->save();
\Mail::send('admin_email_tpl', //admin tpl
array(
'sno' => $request->get('sno'),
'name' => $request->get('name'),
'email' => $request->get('email'),
'files' => $request->post('files'),
), function($message) use ($request, $files)
{
$message->from('123#123foobar.com');
$message->to('123#123foobar.com');
$message->subject('Thank You');
if(count($files) > 0) {
foreach($files as $file) {
$message->attach($file->getRealPath(), array(
'as' => $file->getClientOriginalName(),//custom name
'mime' => $file->getMimeType())
);
}
}
});
}

laravel multiple images update function

i am new for laravel, i am not able to save the files in database on update function can any one help me for this,I have two related tables where one is a ticekt table and the other a one a documents table. In the documents table are the columns id, doc_name,doc_path,user_id and service_id. I'm trying to edit multiple images when editing a service. documents table not updating remaining things update successful
Cread service code
public function store(Request $request)
{
$rules = [
'email' => 'required|string|max:255',
'typeofservice' => 'required',
'companyname' => 'required',
'representative'=> 'required',
'phone' => 'required',
'services' => 'required',
'applicant' => 'required',
//'document' => 'required',
//'document.*' => 'required',
'remark' => 'required',
];
$validator = Validator::make($request->all(),$rules);
if($validator->fails()){
return back()->with('warning','please Fill manadatory fields');
} else {
//$dates = ;
//dd($dates);
$ticket = new Ticket([
'user_id' => Auth::user()->id,
'ticket_id' => strtoupper(str_random(10)),
'email'=>$request->input('email'),
'typeofservice' => $request->input('typeofservice'),
'companyname' => $request->input('companyname'),
'representative' => $request->input('representative'),
'phone' => $request->input('phone'),
'services' => $request->input('services'),
'applicant' => $request->input('applicant'),
'remark' => $request->input('remark'),
'ticket_submit_date' => date('d-M-Y'),
'status' => "1",
]);
//dd($ticket);
$ticket->save();
$userId = Auth::id();
$last_id = DB::getPdo()->lastInsertId();
if($ticket) {
if($request->hasfile('documents')) {
foreach($request->file('documents') as $doc)
{
$name = $doc->getClientOriginalName();
$destinationPath = 'public/documets/';
$documentPath = date('YmdHis') . "." . $doc->getClientOriginalExtension();
$doc->move($destinationPath, $documentPath);
Document::create([
'doc_name' => $name,
'doc_path' => $documentPath,
'user_id' => $userId,
'ser_id' => $last_id,
]);
}
}
//return $last_id;
$ticket_details = DB::table('ticket')->where('id','=',$last_id)->first();
$users = User::where('id','=',$ticket_details->user_id)->first();
$ticketid = $ticket_details->ticket_id;
$username = $users->first_name.' '.$users->last_name;
$mdata = ['ticketid'=>$ticketid,'name'=>$username];
$user['to']= $users->email;
Mail::send('emails.user_create_application',$mdata,function($message) use ($user){
$message->to($user['to']);
$message->subject('User Create Application');
});
return back()->with("success","Service Requiest Created Successfully! your tracking id:#$ticket->ticket_id" );
}
}
}
For uddate function given below
public function udateuserticket(Request $request, $id){
$rules = [
'email' => 'required|string|max:255',
'typeofservice' => 'required',
'companyname' => 'required',
'representative'=> 'required',
'phone' => 'required',
'services' => 'required',
'applicant' => 'required',
//'document' => 'required',
//'document.*' => 'required',
'remark' => 'required',
];
$email = $request->email;
$typeofservice = $request->typeofservice;
$companyname = $request->companyname;
$representative = $request->representative;
$phone = $request->phone;
$services = $request-> services;
$applicant = $request->applicant;
$remark = $request->remark;
$updateuserticket = Ticket::where('id','=',$id)->update([
'email' => $email,'typeofservice' =>$typeofservice, 'companyname' => $companyname, 'representative' => $representative,'phone' => $phone,'services' => $services, 'applicant' => $applicant, 'remark' => $remark ]);
$userId = Auth::id();
$last_id = DB::getPdo()->lastInsertId();
if($updateuserticket){
if($request->hasfile('documents')) {
foreach($request->file('documents') as $doc)
{
$name = $doc->getClientOriginalName();
$destinationPath = 'public/documets/';
if(File::exists($destinationPath)){
File::delete($destinationPath);
}
$documentPath = date('YmdHis') . "." . $doc->getClientOriginalExtension();
$doc->move($destinationPath, $documentPath);
Document::create([
'doc_name' => $name,
'doc_path' => $documentPath,
'user_id' => $userId,
'ser_id' => $last_id,
]);
}
}
$ticket_details = DB::table('ticket')->where('id','=',$last_id)->first();
//$users = User::where('id','=',$ticket_details->user_id)->first();
//$ticketid = $ticket_details->ticket_id;
//$username = $users->first_name.' '.$users->last_name;
return redirect('showtickets')->with('success','Ticket Updated Successfully!');
}
}
for view
#foreach( $documents as $doc )
<div class="col-md-6">
<input id="documents" type="file" class="form-control" name="documents[]" value="" required>
<img src="{{ url('/') }}/public/documets/{{ $doc->doc_path }}" alt="user-img" class="img-width" style="width:30px;height:30px;">
</div>
#endforeach
This one update only details not able to update documents can you please guid anyone where i am wrong

Laravel Livewire Mixed Content error in production

I deployed a Laravel-Livewire on Digital Ocean and now I'm having a Mixed content problem when I try to upload a file.
Here is the error:
UploadManager.js:131 Mixed Content: The page at 'https://intake.freejiji.ca/clients/3/extensions' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://intake.freejiji.ca/livewire/upload-file?expires=1625251608&signature=9d98c598db4f6fccc01c009bcfc3051c6a97b56f4058f4d9489a8d30d6d497c2'. This request has been blocked; the content must be served over HTTPS.
The error happens when after I click "Select File" and chose the .csv file I want. Since I'mdoing this on a livewire component I'm not sure how to fix this so that the request goes over HTTPS instead of HTTP.
I was able to fix similar problems on the app by changing "asset()" with "secure_asset()"
and "route()" with "secure_url()" but in this case I'm not sure what to do.
Here is the whole "Import" component:
<?php
namespace App\Http\Livewire\Modals;
use Validator;
use Livewire\Component;
use App\Http\Traits\Csv;
use App\Models\AccountUser;
use Livewire\WithFileUploads;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Auth;
class ImportExtensions extends Component
{
use WithFileUploads;
public $clientID;
public $showModal = false;
public $upload;
public $columns;
public $fieldColumnMap = [
'first_name' => '',
'last_name' => '',
'email' => '',
'password' => '',
'extension' => '',
'user_type' => '',
];
protected $rules = [
'fieldColumnMap.first_name' => 'required|max:255',
'fieldColumnMap.last_name' => 'required|max:255',
'fieldColumnMap.email' => 'required|max:255',
'fieldColumnMap.password' => 'required|max:255',
'fieldColumnMap.extension' => 'required|max:255',
'fieldColumnMap.user_type' => 'required|max:255',
];
protected $validationAttributes = [
'fieldColumnMap.first_name' => 'First Name',
'fieldColumnMap.last_name' => 'Last Name',
'fieldColumnMap.email' => 'Email',
'fieldColumnMap.password' => 'Password',
'fieldColumnMap.extension' => 'Extension',
'fieldColumnMap.user_type' => 'User Type',
];
public function updatingUpload($value)
{
Validator::make(
['upload' => $value],
['upload' => 'required|mimes:csv'],
)->validate();
}
public function updatedUpload()
{
$this->columns = Csv::from($this->upload)->columns();
$this->guessWhichColumnsMapToWhichFields();
}
public function import()
{
// Validate that you are importing any data
$this->validate();
$importCount = 0;
Csv::from($this->upload)
->eachRow( function ($row) use (&$importCount){
$eachRow = $this->extractFieldsFromRow($row);
// Validate each Row of the csv file
$validatedData = Validator::make([
'first_name' => $eachRow['first_name'],
'last_name' => $eachRow['last_name'],
'email' => $eachRow['email'],
'password' => $eachRow['password'],
'extension' => $eachRow['extension'],
'user_type' => $eachRow['user_type'],
],[
'first_name' => 'required',
'last_name' => 'required',
'password' => 'required|max:255',
'user_type' => 'required|in:user,admin',
'email' => 'required|email|unique:account_users',
'extension' => ['required', 'numeric', Rule::unique('account_users', 'extension')
->where(function($query)
{return $query->where("account_id", $this->clientID);
})],
],);
if($validatedData->fails()){
$this->notify(['error','Oops something went wrong!']);
}else{
AccountUser::create([
'user_id' => Auth::user()->id,
'account_id' => $this->clientID,
'first_name' => $eachRow['first_name'],
'last_name' => $eachRow['last_name'],
'email' => $eachRow['email'],
'password' => $eachRow['password'],
'extension' => $eachRow['extension'],
'user_type' => $eachRow['user_type'],
]);
$importCount++;
}
});
$this->reset();
$this->emit('refreshExtensions');
if($importCount!=0) $this->notify(['success','Successfully Imported '.$importCount.' Extensions']);
}
public function guessWhichColumnsMapToWhichFields()
{
$guesses = [
'first_name' => ['first_name', 'name'],
'last_name' => ['last_name'],
'email' => ['email'],
'password' => ['password', 'pass'],
'extension' => ['extension', 'ext'],
'user_type' => ['user_type', 'user', 'type'],
];
foreach ($this->columns as $column) {
$match = collect($guesses)->search(fn($options) => in_array(strtolower($column), $options));
if ($match) $this->fieldColumnMap[$match] = $column;
}
}
public function extractFieldsFromRow($row)
{
$attributes = collect($this->fieldColumnMap)
->filter()
->mapWithKeys(function($heading, $field) use ($row) {
return [$field => $row[$heading]];
})
->toArray();
return $attributes;
}
public function downloadTemplate()
{
$filename = 'extensions_template.xls';
$path = public_path('files/' . $filename);
return response()->download($path, $filename, [
'Content-Type' => 'application/vnd.ms-excel',
'Content-Disposition' => 'inline; filename="' . $filename . '"'
]);
}
}
If you get mixed content problem it is mostly about you fetching the assets or resources from different http scheme. Here you are using HTTP to fetch data in HTTPS site. Change all the links to have HTTPS link.
If you want to force all the routes to use https you can achieve this by using following code.
if(env('APP_ENV', 'production') == 'production') { // use https only if env is production
\URL::forceScheme('https')
}
The above should solve your problem as all contents now will load from https.

syntax error, unexpected token "<" (View: /Users/pathparakh/Projects/store/resources/views/product.blade.php) in laravel?

There are an error showing when i add #if ({{Auth::user()->utype}} == "ADM") Line of code in product.blade.php.
</head>
#if ({{Auth::user()->utype}} == "ADM")
<body>
</body>
#endif
This is my controller named ProductController.
public function index()
{
$products = Product::all();
return view('product', compact('products'));
}
public function create()
{
return view('product');
}
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'brand' => 'required',
'detail' => 'required',
'size' => 'required',
'type' => 'required',
'price' => 'required',
'image' => 'required',
]);
$image = $request->file('image');
$new_name = rand().'.'.$image->getClientOriginalExtension();
$image->move(public_path('images'), $new_name);
$form_data = array(
'image' => $new_name,
'name' => $request->input('name'),
'size' => $request->input('size'),
'type' => $request->input('type'),
'price' => $request->input('price'),
'detail' => $request->input('detail'),
'brand' => $request->input('brand'),
);
Product::create($form_data);
return redirect()->route('product.index')->withSuccess('Done');
}
enter image description here
Please help me to solve the mistake.
You are already using blade directive, so no need to put {{}}, inside #if or any other directive try this
#if (Auth::user()->utype == "ADM")
<body>
</body>
#endif

Resources