Laravel 5.1 validation - validation

when I use validation in my controller or in a separate request file to validate request of form , it just redirect to itself. But when i remove the validation form just normally update the information please help me.
Here is the route:
Route::group(['prefix' => '{university}'], function() {
Route::Resource('instructor', 'university\univInstructorController');
});
Controller:
<?php
namespace App\Http\Controllers\university;
use App\Http\Requests\university\instructor\instructorUpProfileReq;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\instructor;
use App\university;
use Illuminate\Support\Facades\Redirect;
class univInstructorController extends Controller
{
public function update($university,$id, Request $request)
{
if($universities=university::whereuniversityName($university)->first()){
if($instructors = instructor::find($id)){
$this->validate($request, [
'name' => 'required|alpha|min:3',
'lName' => 'required|alpha|min:3',
'gender' => 'required|alpha',
'birth_date' => 'date',
'degree_type' => 'required|alpha',
'academic_degree' => 'required|alpha',
'phone' => 'max:15',
'address' => 'alpha_dash|min:4',
]);
$input = $request->all();
$instructors->update($input);
return Redirect::action('university\univInstructorController#show',['universities'=>$university,'id'=>$id]);
}
else{
return view('errors.404');
}
}
else{
return view('errors.404');
}
}
}

Related

Validation in Fast Excel package Laravel

ImportController
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Talent\ImportData\Requests\ImportDataRequest;
use Illuminate\Support\Facades\Hash;
use Rap2hpoutre\FastExcel\FastExcel;
class ImportController extends Controller
{
public function __construct(private User $user)
{
}
public function import(ImportDataRequest $request)
{
$validated = $request->validated();
$collection = (new FastExcel)->import($validated['file'], function ($rows) {
$user = $this->user->create([
'name' => $rows['First Name'] . " " . $rows['Last Name'],
'email' => $rows['Email'],
'password' => Hash::make('Introcept#123'),
'role' => $rows['Role']
]);
$employee = $user->employees()->create([
'status' => $rows['Status'],
'first_name' => $rows['First Name'],
'last_name' => $rows['Last Name'],
'email' => $rows['Email'],
'contact_number' => $rows['Contact Number'],
'date_of_birth' => $rows['Date of Birth'],
'current_address' => $rows['Current Address'],
'pan_number' => $rows['Pan Number'],
'bank_account_number' => $rows['Bank Account Number'],
]);
$education = $employee->education()->create([
'education_level' => $rows['Education Level'],
'passed_year' => $rows['Passed Year'],
'institution' => $rows['Institution'],
]);
$employment = $employee->employment()->create([
'organization' => $rows['Organization'],
'join_date' => $rows['Join Date'],
'current_position' => $rows['Current Position'],
'work_schedule' => $rows['Work Schedule'],
'team' => $rows['Team'],
'manager' => $rows['Manager'],
'superpowers' => $rows['Superpower'],
]);
$employment->manages()->create([
'employee_id' => $rows['Manages'],
]);
});
}
}
ImportData Request
<?php
namespace App\Talent\ImportData\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ImportDataRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array<string, mixed>
*/
public function rules()
{
return [
'file'=>'required|mimes:csv,xlsx'
];
}
}
I am creating an API where the admin can import data from an excel file. Here, I am using the Fast Excel package in order to import data. Everything is working fine, but I have no idea how I can validate excel data before saving it into the database. I am pretty new to Laravel and any help will be really appreciated. Thank you

api route laravel always return error 400

I have route api.php like so
Route::group(['middleware' => ['jwt.verify']], function() {
Route::get('logout', [ApiController::class, 'logout']);
Route::get('pengguna', [ApiController::class, 'getAuthenticatedUser']);
Route::get('get_kabupaten/{provid}', [KabupatenController::class, 'get_kabupaten']);
Route::get('get_kecamatan/{kabid}', [KecamatanController::class, 'get_kecamatan']);
Route::get('get_kelurahan/{kecid}', [DesaController::class, 'get_kelurahan']);
Route::get('get_bencana', [JenisbencanaController::class, 'get_bencana']);
Route::get('saport', [ReportController::class, 'get_laporan']);
Route::post('saport/create', [ReportController::class, 'store']);
Route::get('saport/{id}', [ReportController::class, 'show']);
// Route::get('laporan', [LaporanController::class, 'get_laporan']);
// Route::post('laporan/create', [LaporanController::class, 'store']);
// Route::get('laporan/{id}', [LaporanController::class, 'show']);
// Route::put('update/{product}', [LaporanController::class, 'update']);
// Route::delete('delete/{product}', [LaporanController::class, 'destroy']);
});
all everything else work except
Route::get('pengguna', [ApiController::class, 'getAuthenticatedUser']);
Route::get('saport', [ReportController::class, 'get_laporan']);
Route::post('saport/create', [ReportController::class, 'store']);
Route::get('saport/{id}', [ReportController::class, 'show']);
and this my reportcontroller
<?php
namespace App\Http\Controllers;
use App\Models\Laporan;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Validator;
use Auth;
class ReportController extends Controller
{
public function get_laporan()
{
$laporan=Laporan::where('user_id', Auth::id())->get();;
return response()->json(compact('laporan'));
}
public function store(Request $request)
{
$data = $request->only( 'desa_id','bencana_id','koordinat','korban_kk','korban_orang','sebab_bencana');
$validator = Validator::make($data, [
'desa_id' => 'required',
'bencana_id' => 'required',
'koordinat' => 'required',
'korban_kk' => 'required',
'korban_orang' => 'required',
'sebab_bencana' => 'required',
]);
//Send failed response if request is not valid
if ($validator->fails()) {
return response()->json(['error' => $validator->messages()], 200);
}
$laporan = new Laporan;
$laporan->bencana_id = $request->bencana_id;
$laporan->desa_id= $request->desa_id;
$laporan->koordinat= $request->koordinat;
$laporan->user_id= Auth::id();
$laporan->korban_kk= $request->korban_kk;
$laporan->korban_orang= $request->korban_orang;
$laporan->sebab_bencana= $request->sebab_bencana;
$laporan->bantuan_diperlukan= $request->bantuan_diperlukan;
$laporan->respon_instansi= $request->respon_instansi;
$laporan->lokasi_pengungsian= $request->lokasi_pengungsian;
$laporan->pengungsi_kk= $request->pengungsi_kk;
$laporan->pengungsi_orang= $request->pengungsi_orang;
$laporan->permintaan_bantuan= $request->permintaan_bantuan;
$laporan->save();
return response()->json([
'success' => true,
'message' => 'laporan telah di input',
'data' => $laporan
], Response::HTTP_OK);
}
public function show($id)
{
$laporan=Laporan::where('user_id', Auth::id())->find($id);;
if (!$laporan) {
return response()->json([
'success' => false,
'message' => 'Sorry, Laporan not found.'
], 400);
}
return response()->json(compact('laporan'));
}
}
i have rename int from laporan to report to saport, create new controller, and make it HTTPS for saport always return 400.
as far as i know the structure of controler the same with other controller, couse i use meke:controller, and why it return 400 400 Bad Request.
and i make new basic route, and it return 400
Route::get('saport', function () {
return 'Hello World';
});
cahche:clear
route:clear
dumptautoload
trying remove saport from outside jwt,verify
all return 400
i have try all.
btw in local it run like charm, it case only in sharehosting.
i think it postman issue, not laravel. but if any solve for it issue please tell me

Laravel - Maatwebsite Excel import stored in storage only but not in DB

I am importing Excel File using Laravel-8 endpoints and Maatwebsite-3.1 package.
The way I did it is that, the Uploaded Excel file will first get to the storage (storage/file_imports/student_imports). Then Laravel pickes it up from there, stores it into the DB table through StudentImport using Maatwebsites.
StudentImport:
<?php
namespace App\Imports;
use App\Models\User;
use App\Models\Student;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Password;
use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\SkipsErrors;
use Maatwebsite\Excel\Concerns\SkipsOnError;
use Maatwebsite\Excel\Concerns\SkipsFailures;
use Maatwebsite\Excel\Concerns\SkipsOnFailure;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Validators\Failure;
use Throwable;
class StudentImport implements
ToModel,
WithValidation,
WithHeadingRow,
SkipsOnError,
SkipsOnFailure,
WithBatchInserts
{
protected $companyId;
public function __construct()
{
$this->companyId = Auth::user()->company_id;
}
use Importable, SkipsErrors, SkipsFailures;
public function model(array $row)
{
$student_data = [
'first_name' => $row[0],
'other_name' => $row[1] ?? '',
'last_name' => $row[2],
'email' => preg_replace('/\s+/', '', strtolower($row[3])),
'gender' => $row[4],
'nationality_id' => $this->getNationality() ?? '',
'school_id' => Auth::user()->school_id,
];
$student = Student::create($student_data);
if (User::where('email', '=', $student->email)->exists()) {
$user = User::update([
'first_name' => $student->first_name,
'other_name' => $student->other_name,
'last_name' => $student->last_name,
'complete_profile' => 1,
'active' => 1,
'user_type' => 'Driver',
'company_id' => Auth::user()->company_id,
'updated_at' => date("Y-m-d H:i:s"),
'updated_by' => Auth::user()->id,
]);
}else{
$user = User::create([
'email' => $student->email,
'username' => strtok($row[3], '#'),
'password' => bcrypt("123456"),
'first_name' => $student->first_name,
'other_name' => $student->other_name,
'last_name' => $student->last_name,
'activation_token' => str_random(10),
]);
}
}
public function headingRow(): int
{
return 1;
}
public function getRowCount(): int
{
return $this->rows;
}
public function customValidationAttributes()
{
return [
'0' => 'First Name',
'1' => 'Other Name',
'2' => 'Last Name',
'3' => 'Email',
'4' => 'Gender',
];
}
public function rules(): array
{
return [
'*.0' => [
'required',
'string',
'max:50'
],
'*.1' => [
'nullable',
'string',
'max:50'
],
'*.2' => [
'required',
'string',
'max:50'
],
'*.3' => [
'required',
'email',
'max:100',
Rule::unique('studentss')->where(function ($query) {
return $query->where('school_id', Auth::user()->school_id);
})
],
'*.4' => [
'required',
'string',
'max:20'
],
];
}
public function batchSize(): int
{
return 1000;
}
public function chunkSize(): int
{
return 1000;
}
public function onFailure(Failure ...$failures)
{
// Handle the failures how you'd like.
}
public function customValidationMessages()
{
return [
'1.in' => 'Custom message for :attribute.',
'nim.unique' => 'Custom message',
];
}
}
Controller:
public function importStudent(Request $request)
{
try {
$user = Auth::user()->id;
$validator = Validator::make($request->all(), [
'document' => 'file|mimes:xlsx|max:10000',
]);
if($validator->fails()) {
return $this->error($validator->errors(), 401);
} else {
$check = User::where('id', $user)->pluck('id');
if($check[0] !== null || $check[0] !== undefined) {
$file = $request->file('document');
$file->move(public_path('storage/file_imports/student_imports'), $file->getClientOriginalName());
Excel::import(new StudentImport, public_path('storage/file_imports/student_imports/' . $file->getClientOriginalName() ));
return $this->success('Students Successfully Imported.', [
'file' => $file
]);
} else {
return $this->error('Not allowed', 401);
}
}
} catch(\Exception $e) {
return $this->error($e->getMessage());
}
}
As I stated earlier it will first store the Excel file into:
storage/file_imports/student_imports
Then pick it from there and store in the DB.
This code is in the controller above.
The file is store in the
public/storage/file_imports/student_imports
as expected, but nothing is found in the DB. Yes it displays Success with no error.
What could be the problem and how do I resolve it?
Thanks
model method in your StudentImport class must return new instance of Eloquent model.
You shouldn't make create or update method call through your model in here.
Maatwebsite-Excel manage your insert process with own manager. Check source code.
https://github.com/Maatwebsite/Laravel-Excel/blob/3.1/src/Imports/ModelImporter.php#L74
https://github.com/Maatwebsite/Laravel-Excel/blob/3.1/src/Imports/ModelImporter.php#L92
https://github.com/Maatwebsite/Laravel-Excel/blob/3.1/src/Imports/ModelManager.php#L45
https://github.com/Maatwebsite/Laravel-Excel/blob/3.1/src/Imports/ModelManager.php#L64

Undefined property: App\Http\Controllers\ProfessionalsController::$user

I want to add the user while adding a vendor, but it shows me error. I have created the object of class User. This is my code:
<?php
namespace App\Http\Controllers;
use Session;
use App\Vendors;
use App\User;
use App\Category;
use App\Location;
use Illuminate\Http\Request;
class VendorsController extends Controller
{
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|min:2|max:20',
'email' => 'required|email|unique:users,email'
]);
$data = array(
'name' => $request->name,
'email' => $request->email,
'role' => 'Vendor'
);
$this->user->fill($data);
$this->user->save();
$professional = Professional::create([
'user_id' => $this->user,
'contact_number' => $request->contact_number,
'address' => $request->address,
'about_us' => $request->about_us,
'category_id' => $request->category_id
]);
return redirect()->back();
}
}
But I am getting this error:
Undefined property: App\Http\Controllers\ProfessionalsController::$user
Any help will be appreciated.

Laravel 5.8 register redirect

I'm using Laravel 5.8, still new to PHP and Laravel. When I register, it returns the user in JSON format which is normal from the Register Users.php register function. However, I have a redirectTo() function which should take care of the redirect and redirect the user to some pages a specified, but it's not working. I've tried overriding the redirectPath() function as well which isn't working.
The redirect works perfectly for the login controller.
Any solution or pointers would be appreciated. See RegisterController below.
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Auth;
class RegisterController extends Controller
{
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
//public $redirectTo = '/home';
protected function redirectPath()
{
$role = Auth::user()->role;
if ($role === 'candidate') {
return '/candidate_dashboard';
} elseif ($role === 'employer') {
return '/employer_dashboard';
} elseif ($role === 'contractor') {
return '/contractor_dashboard';
}
}
public function __construct()
{
$this->middleware('guest');
}
protected function validator(array $data)
{
try {
return Validator::make($data, [
'first_name' => ['required', 'string', 'max:255'],
'last_name' => ['required', 'string', 'max:255'],
'role' => ['required', 'string', 'max:50'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
} catch (Illuminate\Database\QueryException $th) {
return back()->withError($th->getMessage())->withInput();
}
}
protected function create(Request $data)
{
try {
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'role' => $data['role'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
} catch (Illuminate\Database\QueryException $th) {
return back()->withError($th->getMessage())->withInput();
}
}
}

Resources