Laravel laravel-users add fields to CRUD forms - php

I'm using the laravel-users package to add user management functionality to my Laravel 5.7 application but I'm struggling to figure out how to add additional fields to the user create / user edit forms so that they match my user table schema.
Users table definition:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('phone_number', 13);
$table->boolean('is_super_admin')->default(false);
$table->rememberToken();
$table->timestamps();
});
Specifically I want to add the phone_number field to the forms. I've updated the blade template adding in the markup for the field:
<div class="form-group has-feedback row {{ $errors->has('phone_number') ? ' has-error ' : '' }}">
#if(config('laravelusers.fontAwesomeEnabled'))
{!! Form::label('phone_number', __('auth.phone_number'), array('class' => 'col-md-3 control-label')); !!}
#endif
<div class="col-md-9">
<div class="input-group">
{!! Form::text('phone_number', NULL, array('id' => 'phone_number', 'class' => 'form-control', 'placeholder' => __('auth.phone_number'))) !!}
<div class="input-group-append">
<label class="input-group-text" for="phone_number">
#if(config('laravelusers.fontAwesomeEnabled'))
<i class="fa fa-fw {!! __('laravelusers::forms.create_user_icon_username') !!}" aria-hidden="true"></i>
#else
{!! __('auth.phone_number') !!}
#endif
</label>
</div>
</div>
#if ($errors->has('phone_number'))
<span class="help-block">
<strong>{{ $errors->first('phone_number') }}</strong>
</span>
#endif
</div>
</div>
But it seems that the actual creation of the user is handled by the UsersManagementController that's part of the package itself. How can I override this so that I can have it store the new field I've added?

Without reading in detail the full explanation (since I have currently little reputation on the present website to just post a few comments to clarify the question, rather than an attempt an answer...)
here is some advice ;)
You probably need to go into the UsersManagementController and edit the update function to allow to save the newly added field "phone_number".
Most likely your controller would be located in:
app/Http/Controllers/UsersManagementController.php
the function you need to edit will look something like this
public function update(Request $request, $id) {
// Find the User that needs to be updated
$user = Post::find($id);
$user->phone_number = $request->input('phone_number');
//... some more code here
$user->save();
return //whatever is returned here... potentially redirected
}
To find all list of routes, in case this is the issue and consecutively adapt your form post to submit the data to the correct controller (this will list all you currently managed routes):
php artisan route:list
If there is no controller you should create one and make sure to add it into the:
routes/web.php
Hope this helps

Related

Updating/Adding value to array in Laravel 8

I am new developer, and I seem to be stuck on handling arrays in laravel. I am using Laravel 8, and I cant seem to solve this situation.
I am building an internal recruitment site, where once a manager posts a job, employees will be able to apply to those specific jobs. I have defined the table in the database to have the "applicants" as an array consisting of the user_id's. However, I seem to not be able to add more than one array to it.
Below is my Recruitment Model
class Recruitment extends Model
{
use HasFactory;
protected $fillable = [
'title',
'salary',
'term_start',
'term_end',
'deadline',
'details',
'status',
'applicants',
];
public function user(){
return $this->belongsTo("\App\Models\User");
}
protected $casts = [
'applicants' => 'array'
];
}
Next is my migration (I am using text format, because the DB on the server is older and does not support json)
public function up()
{
Schema::create('recruitments', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->decimal('salary', 10, 2);
$table->date('term_start');
$table->date('term_end');
$table->date('deadline');
$table->longText('details');
$table->string('status');
$table->text('applicants')->nullable();
$table->timestamps();
});
}
Here is my blade
<div class="container">
<div class="row">
<div class="card col-sm-12 py-3">
<div class="card-header border d-flex justify-content-between align-items-center">
<h3 class="w-75">{{ $job->title }}</h3>
<div class="w-25">
<p class="my-0 my-0">Created at: <span class="text-info">{{ $job->created_at }}</span></p>
<p class="my-0 my-0">Last updated at: <span class="text-primary">{{ $job->updated_at }}</span></p>
</div>
</div>
<div class="card-body">
// display job details here
<form action="{{ route('add-applicant', ['id' => $job->id ]) }}" method="POST" class="col-sm-12 d-flex justify-content-center align-items-center">
#csrf
<input type="text" name="user_id" id="user_id" value="{{ Auth::user()->id }}" hidden>
<button type="submit" class="btn btn-success w-25">Apply</button>
</form>
</div>
</div>
</div>
</div>
and lastly my controller
public function addApplicant($id, Request $reqst){
$job = Recruitment::find($id);
$user[] = $reqst->user_id;
$job->applicants = $user;
$job->save();
return redirect()->back();
}
While this controller will be able to save an array, it unfortunately overwrites the already existing one (let's say a second user applied). When I try to use an array_push, it does nothing, and I still end up with just one value in the array.
Sorry this was a bit of a read, but I appreciate any help I cen get with this. Thanks
Try in
public function addApplicant($id, Request $reqst){
$job = Recruitment::find($id);
$job->applicants = $reqst->user_id;
$job->save();
return redirect()->back();
}
and in Recruitment model should have
public function user()
{
return $this->belongsTo(User::class, 'applicants');
}
and migration file
$table->integer('applicants')->nullable();

Laravel PHP form submition, breaks text when displaying results?

So I have a ToDo List and really strange problem.
So I have a form where user writes the Title and task description, task description is done as textarea, after that the user presses the submit button and submits the Task, which then redirects user to the "Home page" and displays all pending tasks.
The problem is when user presses "ENTER" inside the texarea the text "breaks" and doesn't align with the HTML div tag.( As shown in the picture below (TASK 3 and TASK 2))
This is my "Display all tasks" code
> #foreach ($tasks as $task)
> <div class="Task">
> <h1>{{ $task->TaskName }}</h1>
> <div class="TaskDescription">
> <p>{{ $task->TaskDescription }}</p>
> </div>
> </div>
> #endforeach
,this is my "Create new task" form
<div class="FormContainer">
<form method="POST" action="/tasks" class="form_group_vertical">
#csrf
<input name="TaskName" placeholder="Task name..." class="lineInput">
<textarea name="TaskDescription" placeholder="Task description..." class="Form_TextArea"></textarea>
<button class="btn_submit" type="submit">Create new Task</button>
</form>
and this is how I store all my tasks
public function storeTasks(){
// return request()->all(); data displayed in JSON
Task::create([
'TaskName' => request('TaskName'),
'TaskDescription' => request('TaskDescription')
]);
return redirect('/tasks');
}
and this is my migration up function
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->id();
$table->string('TaskName');
$table->text('TaskDescription');
$table->timestamps();
});
}
So far I had tried, changing how the data is saved,
tried replacing the {{ }} with {!! !!}, tried changing databases, and tried completely rewriting the form - I couldn't find any fix with this aproach.
Use nl2br
#foreach ($tasks as $task)
<div class="Task">
<h1>{{ $task->TaskName }}</h1>
<div class="TaskDescription">
<!-- Change here -->
<p>{!! nl2br(trim($task->TaskDescription)) !!}</p>
<!-- OR -->
<p>{!! str_replace(array("\r\n", "\r", "\n"), "<br />", $task->TaskDescription) !!}</p>
</div>
</div>
#endforeach
Having the textarea inside <pre> works too.
SOLUTION !!!
To fix my issue I had to replace the $table->text('TaskDescription') and change it into $table->longText('TaskDescription')
Replaced text with longtext
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->id();
$table->string('TaskName');
$table->longText('TaskDescription');
$table->timestamps();
});
}

Missing route parameter for Route URI using Laravel?

I'm trying to create a Laravel Notification. I created a table called send_profiles. When a Candidate is logged in and searching through jobs, he can send his job profile to the employer. All of that data is in a table called job_seeker_profiles. I'm developing a Job Search type of application.
I created a new Notification class called SendProfile.php:
public function toDatabase($notifiable)
{
$user = Auth::user();
return [
'user_id' => Auth::user()->id,
'employer_profile_id' => DB::table('send_profiles')->where('user_id', $user->id)->orderBy('id', 'desc')->offset(0)->limit(1)->get('employer_profile_id'),
];
}
I don't know the best way to go about this but anyway this is my route.
web.php:
Route::get('/admin/job-seeker/search/employer/{employerId}/post-a-job/{jobPostId}/send-profile', 'AdminEmployerJobPostsController#sendProfile')->name('admin.employer.post-a-job.show.send-profile')->middleware('verified');
AdminEmployerJobPostsController.php:
public function sendProfile($employerId, $jobPostId)
{
$user = Auth::user();
$jobSeekerProfile = JobSeekerProfile::all()->where('user_id', $user->id)->first();
$employerProfile = EmployerProfile::limit(1)->where('id', $employerId)->get();
$jobPosts = JobPosts::all();
$jobPost = JobPosts::findOrFail($jobPostId);
$user->sendProfile()->create();
$employerProfile->notify(new SendProfile());
return back()->with('send-profile', 'Your Profile has been sent!');
}
This is my error:
Missing required parameters for [Route: admin.employer.post-a-job.show.send-profile] [URI: admin/job-seeker/search/employer/{employerId}/post-a-job/{jobPostId}/send-profile]. (View: /Applications/XAMPP/xamppfiles/htdocs/highrjobs/resources/views/admin/employer/post-a-job/show.blade.php)
show.blade:
#extends('layouts.admin')
#section('pageTitle', 'Create a User')
#section('content')
#include('includes.job_seeker_search_employers')
<!-- The Modal -->
<div class="modal" id="myModal5">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">{{ $jobPost->job_title }}</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<h5>{{ $jobPost->job_description }}</h5>
</div>
<!-- Modal footer -->
<div class="modal-footer">
{!! Form::open(['method'=>'POST', 'action'=>'AdminEmployerJobPostsController#sendProfile', 'files'=>true, 'style'=>'width: 100%;']) !!}
<div class="form-group">
{!! Form::hidden('user_id', Auth::user()->id, ['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::hidden('employer_profile_user_id', $employerProfile->id, ['class'=>'form-control']) !!}
</div>
<div class="row">
<div class="col">
{!! Form::button('Back', ['class'=>'btn btn-danger btn-block float-left', 'data-dismiss'=>'modal']) !!}
</div>
<div class="col">
{!! Form::submit('Send Profile', ['class'=>'btn btn-primary btn-block float-right']) !!}
{!! Form::close() !!}
</div>
</div>
<br><br><br><br>
</div>
</div>
</div>
</div>
#stop
If I remove the form, I at least don't get an error. So I actually think there is an issue with the form.
To be clear, all I want is to insert the user_id and the employer_profile_id into the send_profiles table and then send a notification to the employer.
Your route specifies a GET request to a URL that contains certain parameters:
/admin/job-seeker/search/employer/{employerId}/post-a-job/{jobPostId}/send-profile
Your form is using AdminEmployerJobPostsController#sendProfile as an action; this is translated into a URL by searching the route list, and choosing what Laravel thinks is most appropriate. Since you haven't passed anything to fill the employerId and jobPostId parameters, you're getting this error when the URL is generated.
Even if you could get the URL generated, you'd have a problem because your form is sending a POST request to this GET route.
What you need to do is ensure you have a POST route pointing to a new controller method. You won't pass any parameters to this route in the URL, so your controller method will only typically accept a Request object as a parameter. Second thing you should do is specify your form's target more accurately. Pass in the route name instead of making it guess.
public function sendProfile(Request $request)
{
// you get this here so no need to pass it in the form
$user = Auth::user();
// your relations should be set up so you don't need to do this:
// $jobSeekerProfile = JobSeekerProfile::all()->where('user_id', $user->id)->first();
// instead do this:
$jobSeekerProfile = $user->jobSeekerProfile();
// a simple find is much neater than what you had
$employerProfile = EmployerProfile::find($request->job_seeker_profile_user_id);
// not sure why this is here?
$jobPosts = JobPosts::all();
// also your form isn't passing a job post ID
$jobPost = JobPosts::findOrFail($request->jobPostId);
// ??? creating an empty something?
$user->sendProfile()->create();
$employerProfile->notify(new SendProfile());
return back()->with('send-profile', 'Your Profile has been sent!');
}

Laravel how to echo selected a value in a dropdown using blade when updating a specific resource

I want to echo the selected value when I edit a specific resource in my table. When I edit the specific resource it should display the current data in my dropdown but in the real scenario it displays the first one on the list which is wrong. So how can I echo the selected value in the options of the dropdown using blade in laravel?
Here is some sample of my code in the view below
<!-- Shows Field -->
<div class="form-group col-sm-6">
{!! Form::label('show_id', 'Shows:') !!}
{!! Form::select('show_id', $shows, $shows, ['class' => 'form-control input-md','required'])!!}
</div>
{{-- {{ $channelshows->channel->name }} --}}
<!-- Client Id Field -->
<div class="form-group col-sm-6">
{!! Form::label('channel_id', 'Channels:') !!}
{!! Form::select('channel_id', $channel, $channel, ['class' => 'form-control input-md','required'])!!}
</div>
<!-- Submit Field -->
<div class="form-group col-sm-12">
{!! Form::submit('Save', ['class' => 'btn btn-primary']) !!}
Cancel
</div>
and here is the code in my controller below.
public function edit($id)
{
$channelshows = $this->channelshowsRepository->findWithoutFail($id);
$shows = Show::pluck('name', 'id');
$channel = Channel::pluck('name', 'id');
if (empty($channelshows)) {
Flash::error('Assigned show not found');
return redirect(route('admin.channelshows.index'));
}
return view('admin-dashboard.channelshows.edit', compact('shows', $shows), compact('channel', $channel))->with('channelshows', $channelshows);
}
Everything here works fine even if I updated the specific resource. I just want to auto populate or select the current value of the resource that I will update because when I edit the specific resource it shows the first one on the list.
Am I going to use an #if statement in blade? But how can I do it using the blade template in my select form. Can somebody help me?
Appreciate if someone can help.
Thanks in advance.
Here is an example:
Open form:
{{ Form::model($service, array('route' => array('services.update', $service->id))) }}
Select form field:
<div class="form-group">
{{ Form::label('Related Agreement') }}
{{ Form::select('agreement', $agreementsList, null, array('class'=>'form-control', 'placeholder'=>'Please select ...')) }}
</div>
In Controller:
$agreementsList = Agreement::all()->sortBy('name', SORT_NATURAL | SORT_FLAG_CASE)->pluck('name', 'id');
(Include this when passing data to your view)

Laravel: migration default() field does not work

i having troubles with my migration field default('No description'), i need to save a default value for my null fields on my form, but when i save, my form data stores empty fields.. why? i'm working with Laravel 5.2 and it is my code:
public function up()
{
Schema::create('combos', function (Blueprint $table) {
$table->increments('id');
$table->string('item_name');
$table->string('description')->nullable()->default('No description');
$table->decimal('price', 5, 2);
$table->decimal('buy_price', 5, 2);
$table->timestamps();
});
}
My view:
<div class="form-group">
{!! Form::label('item_name','Item: ',['class'=>'control-label col-md-2']) !!}
<div class="col-md-7" >
{!! Form::text('item_name',null,['class'=>'form-control','placeholder'=>'Enter a item name','required','min'=>5]) !!}<br/>
</div>
</div>
<div class="form-group">
{!! Form::label('price','Price: ',['class'=>'control-label col-md-2']) !!}
<div class="col-md-7" >
{!! Form::text('buy_price',null,['class'=>'form-control','placeholder'=>'Enter a price','required']) !!}<br/>
</div>
</div>
in your store function do this
$input = $request->all();
$input['description'] = $request->description;
Combos::create($input);

Categories