How to set Unique property to a field in laravel - laravel

I've a table of building in which there is building name in db.when i add building through blade if the building name exist then it can not added. instead of storing it to db i want to show some error.what should i do?
this is my validation
$validator = Validator::make(
$request->all(),
[
'b_name' => 'required|max:20',
],
[
'b_name.required' => '*please fill this field',
]
);
if ($validator->fails()) {
return Response::make([
'message' => trans('validation_failed'),
'errors' => $validator->errors(),
]);
}
if ($validator->passes()) {
$name = $request->input('b_name');
$description = $request->input('b_description');
$created_at = Carbon::now();
$updated_at = Carbon::now();
$array = array('name' => $name, 'description' => $description, 'created_at' => $created_at, 'updated_at' => $updated_at);
Building::insert($array);

$validator = Validator::make(
$request->all(),
[
'b_name' => 'required|max:20|unique:buildings,name',
],
[
'b_name.required' => '*please fill this field',
'b_name.unique' => ('*building name already exists'),
]
);
if ($validator->fails()) {
return Response::make([
'message' => trans('validation_failed'),
'errors' => $validator->errors(),
]);
}
if ($validator->passes()) {
$name = $request->input('b_name');
$description = $request->input('b_description');
$created_at = Carbon::now();
$updated_at = Carbon::now();
$array = array('name' => $name, 'description' => $description, 'created_at' => $created_at, 'updated_at' => $updated_at);
Building::insert($array);
return 1;
}
Response::json(['errors' => $validator->errors()]);
}

If b_name is your input for building name and name is your database field name for Building model then try this code in your validation.
'b_name' => 'required|max:20|unique:App\Building,name'
For more details visit : https://laravel.com/docs/6.x/validation#rule-unique

Your code shoulde be like
$input = $request->all();
$rules = ['b_name' => 'required|required|unique:table_name,b_name|max:20'];
$messages = [
'b_name.required' => '*please fill this field'
'b_name.unique' => 'building name already taken.'
];
$validator = Validator::make($input, $rules, $messages);

Related

Laravel 6 upload file

I have a big struggle about adding file uploading to an existing laravel 6 form.
I want to add the file url to database for future to be displayed (or downloaded).
When i try to do something nothing is happaning, nothing in DB nothing in file dir.
Here is my model:
protected $fillable = [
'age',
'last_rab',
'names',
'email',
'phone',
'last_pos',
'cv',
'msg',
'status'
];
Here is my Controller:
public function store(Request $request)
{
$request->validate([
'names' => 'required',
'age' => 'required',
'last_rab' => 'required',
'last_pos' => 'required',
'phone' => 'required',
'cv' => 'required|mimes:doc,docx,pdf,txt|max:2048',
'msg' => 'required'
]);
if ($request->captcha != 58) {
return redirect()->back()->withInput()->with('warning', 'Wrong');
}
$karieri = new Karieri;
$karieri->age = $request->age;
$karieri->last_rab = $request->last_rab;
$karieri->names = $request->names;
$karieri->email = $request->email;
$karieri->phone = $request->phone;
$karieri->last_pos = $request->last_pos;
if ($request->hasfile('cv')) {
$file = $request->file('cv');
$name = time().'.'.$file->extension();
$file->move(public_path() . '/storage/app/public', $name);
$data = $name;
$karieri->cv = json_encode($data);
}
$karieri->msg = $request->msg;
$karieri->status = 0;
$karieri->save();
return redirect()->back()->with('success', 'Thanks');
}
Can somebody say how to do this?

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

How to validate a string in laravel

I have a textarea where a user can bulk add clients. In the textarea they would add the clients like this
client 1,client1#domain.com,client username 1
client 2,client2#domain.com,client username 2
client 3,client3#domain.com,client username 3
Here is what I have so far
public function bulkClients()
{
$bulk = request('bulk_clients');
$split = explode("\n",$bulk);
foreach($split as $row)
{
$split_row = explode(",", $row);
$name = $split_row[0];
$email = $split_row[1];
$username = $split_row[2];
$validate = Validator::make($email, [
$email => 'email',
$username => 'unique:App\User,username'
]);
if($validate->fails())
{
$messages = $validate->messages();
return response()->json([
'messages' => $messages
]);
}
}
}
What I would like to know is how can I validate that $email is an email or that $username is unique.
The first param of Validator::make should be an array and the second is the rules for the keys of the array.
public function bulkClients()
{
$bulk = request('bulk_clients');
$split = explode("\n",$bulk);
foreach($split as $row)
{
$split_row = explode(",", $row);
$client['name'] = $split_row[0];
$client['email'] = $split_row[1];
$client['username'] = $split_row[2];
$validate = Validator::make($client, [
'email' => 'email',
'username' => 'unique:App\User,username'
]);
if($validate->fails())
{
$messages = $validate->messages();
return response()->json([
'messages' => $messages
]);
}
}
}
You find all available rules in the docs:
$validate = Validator::make([ 'email' => $split_row[1],
'username' => $split_row[2]
], [
'email' => 'string',
'username' => 'unique:App\User,username'
]);
However, for email, I would rather check if its a valid email instead of a string. Thus,
'email' => 'email'
would be recommended.
I would suggest using the validator for the whole array instead of validating it row by row:
$clients = Str::of(request()->get('bulk_clients'))
->explode("\n")
->map(fn ($value) => Str::of($value)->explode(','))
->toArray();
$validator = Validator::make(compact('clients'), [
'clients' => 'array',
'clients.*.0' => 'required|string',
'clients.*.1' => 'required|email',
'clients.*.2' => 'required|unique:App\User,username',
]);

creating default object from empty value in laravel 5

I'm trying to make two functions in controller that have post action and that are in the same page.
My Controller
public function store(Request $request)
{
$status = DB::table('analytics')->where('dienstleistung', '!=', '')->get();
//Save data
$rules = [
'site_id' => 'required',
'dienstleistung' => 'required',
'objekt' => 'required',
'zimmer' => 'required',
'vorname' => 'required',
'name' => 'required',
'strasse' => 'required',
'ort' => 'required',
'plz' => 'required',
'tel' => 'required',
'email' => 'required|email',
'reinigungstermin' => 'required',
'gekommen' => 'required',
'message' => 'required',
'status' => 'required',
'answer' => 'required',
'notiz' => 'required',
'userId' => 'required',
];
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()) {
return Redirect::to('anfrage')
->withErrors($validator)
->withInput();
}
else {
$anfrage = new Analytic();
$anfrage->site_id = Input::get('site_id');
$anfrage->dienstleistung = Input::get('dienstleistung');
$anfrage->objekt = Input::get('objekt');
$anfrage->zimmer = Input::get('zimmer');
$anfrage->vorname = Input::get('vorname');
$anfrage->name = Input::get('name');
$anfrage->strasse = Input::get('strasse');
$anfrage->ort = Input::get('ort');
$anfrage->plz = Input::get('plz');
$anfrage->tel = Input::get('tel');
$anfrage->email = Input::get('email');
$anfrage->reinigungstermin = Input::get('reinigungstermin');
$anfrage->gekommen = Input::get('gekommen');
$anfrage->message = Input::get('message');
$anfrage->status = Input::get('status');
$anfrage->answer = Input::get('answer');
$anfrage->notiz = Input::get('notiz');
$anfrage->userId = Input::get('userId');
try {
$anfrage->save();
flash()->success(trans('app.success'));
return Redirect::to('anfrage');
} catch (\Exception $e) {
Log::writeException($e);
return Redirect::to('anfrage')
->withErrors($e->getMessage())
->withInput();
}
}
}
public function editItem(Request $request) {
$anfrages = Analytic::find($request['id'] );
$anfrages->status = $request->status;
$anfrages->answer = $request->answer;
$anfrages->notiz = $request->notiz;
$anfrages->save();
return response ()->json( $anfrages );
}
My route:
Route::post('anfrage', 'AnfrageController#store');
Route::post ( 'anfrage', 'AnfrageController#editItem' );
EditItem function is OK, it makes changes when I want to edit data, but when I want to store data, message being displayed is:
creating default object from empty value
So, I need to leave active only one of these function, both are not working.

update not being done no errors are showing using query builder laravel 4.2

i have to update a table and change the value inside it and the table have many column inside it. i tried to use query builder and here is my current code
the query is inside the public function ugetstd($id)
public function ugetstd($id) //update
{
$rules = array(
'firstname' => 'required|max:80|regex:/^[\p{L}\p{N} - ]+$/u',
'middlename' => 'required|max:50|regex:/^[\p{L}\p{N} -]+$/u', //more here
);
$messages = array(
'firstname.required' => 'First name is required',
'firstname.max' => 'First name can only contain 80 characters' //more here
);
$validator = Validator::make(Input::all(), $rules, $messages);
if ($validator->fails())
{
return Redirect::to('view_students/' . $id)
->withErrors($validator)
->withInput(Input::except('password'));
}
else
{
DB::table('dbo_students')->where('StudentID', $id )
->update
(
array
(
'FirstName' => Input::get('firstname'),
'MiddleName' => Input::get('middlename'),
'LastName' => Input::get('lastname'),
'CurrentStatusID' => Input::get('scs'),
'Sex' => Input::get('sex'),
'ReligionID' => Input::get('rel'),
'EthnicityID' => Input::get('eth'),
'StreetAddress' => $enAdd,
'CityID' => Input::get('city'),
'YearLevelID' => Input::get('yearlevel'),
'Telephone' => Input::get('telephone'),
'Birthdate' => Input::get('date'),
'Birthplace' => Input::get('birthplace'),
'SchoolLastAttended' => Input::get('schoollastattended'),
'LastGradeCompleted' => Input::get('lastgradecompleted'),
'CurrentModuleLeft' => Input::get('currentmoduleleft'),
'CurrentModuleCriticalLevel' => Input::get('modulecriticallevel'),
'StudentDescription' => Input::get('description')
)
);
return Redirect::to('view_students/' . $id);
}
}
the thing is it does not execute the code. it does not update anything and it does not throw any error. any ideas what i am doing wrong? thanks

Resources