Missing route parameter for Route URI using Laravel? - php

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!');
}

Related

Delete and Update Method of CRUD is not passing all the parameters

I've implemented a modal type Update and Delete functions in my website but it always return Too few arguments to function App\Http\Controllers\AdminController::destroy(), 1 passed in D:\SUDRTest\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54 and exactly 2 expected
it is also the same for the Update function as well
Here is my route for the CRUD
Route::resource('papers', AdminController::class)->only(['edit', 'update', 'destroy']);
Here is the View
<li class="pdfpaperInfo">
<div class="colpdf col-1" data-label="Title:">{{ $paper->PaperTitle }}</div>
<div class="colpdf" data-label="Paper Type:">{{ $paper->PaperType }}</div>
<div class="colpdf" data-label="College:">{{ $paper->College }}</div>
<div class="colpdf" data-label="Author(s):">{{ $paper->Authors }}</div>
<div class="colpdf" data-label="Date Published:">{{ $paper->DatePublished }}</div>
<div class="pdfbtnCont">
<button class="pdfBtn redBtn" onclick="location.href='{{route('MyProfile')}}'">Back</button>
<button class="pdfBtn redBtn" id="modalOneBtn" onclick="location.href='{{route('papers.edit', $paper->PaperID)}}'">Update</button>
<button class="pdfBtn redBtn" id="modalTwoBtn">Delete</button>
</div>
</li>
<div id="modalOne" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="m1Close close">×</span>
<div class="modalinfoCont">
<h2>Update Paper</h2>
#include('admin.updatepaper')
</div>
</div>
</div>
<div id="modalTwo" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="m2Close close">×</span>
<div class="modalTwoCont modalinfoCont">
<h2>Delete Paper</h2>
<br>
Are you sure you want to delete this paper?
<br>
<br>
<div class="modalbtnCont">
<form method="POST" action="{{route('papers.destroy', $paper->PaperID) }}">
#csrf
#method('DELETE')
<button class="redBtn" type="submit">Yes</button>
</form>
<button class="redBtn" type="submit">No</button>
</div>
</div>
</div>
</div>
</div>
and the controller
public function destroy(Papers $paper, $PaperID)
{
$paper=Papers::find($PaperID);
$paper->delete();
return redirect()->back();
}
public function edit(Papers $paper, $PaperID)
{
$paper=Papers::find($PaperID);
return view('admin.updatepaper',compact('paper'));
}
public function update(Request $request,Papers $paper, $PaperID )
{
$request->validate([
'PaperTitle' => 'required',
'PaperType' => 'required',
'file' => [
'required',
File::types('pdf')
->max(12 * 1024),
],
]);
$paper=new Papers();
$file=$request->file;
$filename=time().'.'.$file->getClientOriginalExtension();
$request->file->move('assets', $filename);
$paper->file=$filename;
$paper->DatePublished=$request->DatePublished;
$paper->PaperTitle=$request->PaperTitle;
$paper->PaperType=$request->PaperType;
$paper->Authors=$request->Authors;
$paper->update();
return redirect()->back();
}
I've tried not to do it in modal form and still it kept on displaying the same error and I don't know what is the missing parameter since it doesn't tell me
You need to take another look at route-model binding.
Laravel will by default do the Papers::find($paperID) and pass the Papers model as the Papers $papers argument to your methods.
So the destroy method should be:
public function destroy(Papers $paper)
{
$paper->delete();
return redirect()->back();
}
Of course you can disable route-model binding and do your own thing but it doesn't seem necessary here.
Its not clear what you intend to do in the update method. If you want to create a new paper on update and keep the old one then change $paper->update() to $paper->save() and you should be good. But if you want to do an actual update you should do something like this:
update(Papers $paper, Request $request) {
// validate
$paper->DatePublished=$request->DatePublished;
// update other fields
$paper->save();
return redirect()->back();
}

Cannot find the way to make #if statement works in blade

I'm making a "teacher's" app, and I want to make a log-in page which changes depending if there's registered users in the database or not.
I want to make a redirection button to a create user page if there aren't auth users in database, and to make a select user view if the database have one or more users.
The problem is that I don't know how to exactly do this, 'cause the view always shows me the first statement (what I've got in the if), also if in the database are registered users. Can anyone help me with this please?
This is the blade file:
#if (empty(Auth::user()->id))
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Welcome</h1>
<p>We see there aren't users</p>
</div>
<div id="loginForm">
<button type="button" onclick="window.location='{{ url("/newUser") }}'">Button</button>
</div>
</div>
#else
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Select an user</h1>
</div>
<div id="loginForm"></div>
</div>
#endif
Here you have the controller index method:
public function index()
{
$users = User::all();
return view('/', compact('users'));
}
And finally here you have the page:
The following code is the sample for it, kindly replace code accordingly
#if(!$user)
//show button
#else
//dont show button
#endif
I think your question is you want to check if there is user in database.
So no need to check if the user authenticated but to check if there is user on the database.
In your controller
public function index() {
return view('/', ['users' => User::all()]);
}
and in your blade file
#if(!$users)
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Welcome</h1>
<p>We see there aren't users</p>
</div>
<div id="loginForm">
<button type="button" onclick="window.location='{{ url("/newUser") }}'">Button</button>
</div>
</div>
#else
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Select an user</h1>
</div>
<div id="loginForm"></div>
</div>
#endif
This function will get the current authenticated user: Auth::user(). I guess what you are trying to achieve is #if(empty($users)) where $users is the variable you are passing on controller.
If you want to verify if the user that accessed to that view is authenticated you can simply use #auth and #guest.
Also i would suggest you to change your button to an <a> tag and your href would be <a href="{{ route('route.name') }}" where route.name would be defined in your routes file.
in your controller:
you can create a folder inside views called users and then the index.blade.php (views/users/index.blade.php)
public function index()
{
$users = Users::all();
return view('users.index')->with('users', $users);
}
in your view:
#if(count($users) < 1)
...
#else
...
#endif
count is validating if the $users array length is less then 1 (in other words if the array is empty).
Alternative you can you isEmpty()
#if($users->isEmpty())
...
#else
...
#endif

Use a parameter from URL in a controller Laravel 5.8.22

I'm trying to pass anINT from this URL: myapp.build/courses/anINT (implemented in the CoursesController) to $id in the Lesson_unitsController function below. I've tried a lot of solutions, but I can't seem to get it right.
The function in the CoursesController which implements the url is:
public function show($id)
{
$course = Course::find($id);
return view('courses.show')->with('course', $course);
}
Part of the show.blade.php file is:
#if(!Auth::guest())
#if(Auth::user()->id == $course->user_id)
Edit Course
Lesson Units
{!!Form::open(['action'=> ['CoursesController#destroy', $course->id], 'method' => 'POST', 'class' => 'float-right'])!!}
{{Form::hidden('_method', 'DELETE')}}
{{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
{!!Form::close()!!}
#endif
#endif
The Lesson_unitsController functions are:
public function index()
{
$lesson_units = Lesson_unit::orderBy('title','asc')->paginate(10);
return view('lesson_units.index')->with('lesson_units', $lesson_units);
}
public function specificindex($id)
{
$course = Course::find($id);
return view('lesson_units.specificindex')->with('lesson_units', $course->lesson_units);
}
And the specificindex.blade.php file is:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Dashboard</div>
<div class="card-body">
Create lesson unit
<p>
<h3>Your lesson_units</h3>
#if(count($lesson_units) > 0)
<table class="table table-striped">
<tr><th>Title</th><th></th><th></th></tr>
#foreach($lesson_units as $lesson_unit)
<tr><td>{{$lesson_unit->title}}</td>
<td>Edit</td>
<td>
{!!Form::open(['action'=> ['Lesson_unitsController#destroy', $lesson_unit->id], 'method' => 'POST', 'class' => 'float-right'])!!}
{{Form::hidden('_method', 'DELETE')}}
{{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
{!!Form::close()!!}
</td>
</tr>
#endforeach
</table>
#else
<p>You have no lesson unit.</p>
#endif
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
You are logged in!
</div> </div> </div> </div> </div>
#endsection
The routes in web.php are:
Route::resource('courses', 'CoursesController');
Route::resource('lesson_units', 'Lesson_unitsController');
Route::get('/courses/{id}', 'Lesson_unitsController#specificIndex');
I want that when the link for Lesson Units is clicked on the page, the id in the url is passed to the specificindex function in the Lesson_unitsController. Now, I get just a blank page. What am I doing wrong?
Try to understand the concept of RESTful and CRUD.
By using Route::resource('courses', 'CoursesController');, Laravel has helped you to register the following routes:
Route::get('courses', 'CoursesController#index');
Route::get('courses/create', 'CoursesController#create');
Route::post('courses/{course}', 'CoursesController#store');
Route::get('courses/{course}/edit', 'CoursesController#edit');
Route::put('courses/{course}', 'CoursesController#update');
Route::delete('courses/{course}', 'CoursesController#destroy');
Then, when you make GET request to myapp.build/courses/123, Laravel will pass the request to the show function of your CoursesController like:
public function show(Course $course)
{
return view('lesson_units.index')->with('lesson_units', $course->lesson_units);
}
Laravel will automatically resolve the Course from your database using the parameter passed into the route myapp.build/courses/{course}.
Note: The variable name $course has to match with the one specify in route /{course}.
You don't have a route set up to handle the $id coming in. The resource method within the Route class will provide a GET route into your Lesson_unitsController controller without an expectation of any variable. It is the default index route, and by default doesn't pass a variable.
There are a couple of ways to do this, but the easiest is to just create a new route for your specific need:
Route::get('lesson_units/{id}', 'Lesson_unitsController#specificIndex');
And then make your specificIndex function in your controller with an incoming variable:
public function specialIndex($id)
{
$course = Course::find($id);
// return view to whatever you like
}
HTH

Laravel 5 function redirect to third party url

How do I pass all form data function to third party URL. Suppose my third URL is
`http:\\www.abletoaccess.com\form\request`
For the security reason I don't want to access this URL in form action method or I don't want to post direct form data. I want when I submit the form all data comes in my function and redirect to third party URL with post data and added more parameters.
Any help will be appreciated!!!!
You can handle the request by your controller and then show view and auto-submit it to external url.
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">
Page is loading...
</div>
<div class="panel-body">
{!! Form::open(['url' => $externalUrl, 'method' => 'POST', 'class' => 'form-horizontal', 'id' => 'my-form']) !!}
#foreach ($fields as $key => $value)
{{ Form::hidden($key, $value) }}
#endforeach
{{ Form::hidden('signature', $signature) }}
{!! Form::close() !!}
</div>
</div>
</div>
</div>
</div>
<script>
document.getElementById('my-form').submit();
</script>
Try Following Code:
<form method="post" action={{ action('Controller#method') }}>
<input type="submit" value="add">
</form>
in controller file write below code :
public function method(Request $request)
{
Redirect::away('external url')->withInputs(Input::all());
}
Laravel 5: how to redirect with data to external resource form controller
First of all, this seems not to be Laravel specific issue.
Second, you need to check CURL function in PHP.
PHP CURL
If you can, install Guzzle client that helps with these things.
You can pass the client to your controller and do a post request to another URL like this:
public function someMethod(GuzzleHttp\Client $client)
{
$client->post('http:\\www.abletoaccess.com\form\request', [
'form_params' => [
'param1' => 'something',
...
]
]);
}

Laravel Routing Issues For Modal Form

I have a web app project I've been working on, most of the applications functionality works except for submitting a flag on a resource. I want to use a modal form to submit the data to the database, then on the Flagged view page display all flagged resources Name & Description(from the Resources table) Flag_Reason & Other_Comments(from the Flagged table) I had it working to where it was submitting only the Flag_Reason and Other_Comments and not updating my Resources Table at all. I believe I'm having issues with routes now, because after changing my function to update my Resources table AND create a new Flag entry in the DB I get an error like this
Missing argument 1 for App\Http\Controllers\FlagsController::addFlag()
Here's some of my code, hopefully someone can help me finally figure this out once and for all.
Routes
Route::get('resource', array('as'=>'viewResource', 'uses' => 'ResourceController#resource'));
Route::get('flags', 'FlagsController#index');
Route::post('resource', ['as' => 'resource', 'uses'=>'FlagsController#addFlag']);
///Route::post('resource', ['as' => 'resource', 'uses'=>'FlagsController#postFlag']);///
This route works fine, and only inserts the Flagged table data into the database.
If I modify my route to look like this Route::post('resource/{Resource_ID}', ['as' => 'resource', 'uses'=>'FlagsController#addFlag'])
I receive an error like this
Missing required parameters for [Route: resource] [URI: resource/{Resource_ID}].
Flags Controller
class FlagsController extends Controller
{
public function index()
{
$resources = Resources::where('Flagged', 1)->with('flags')->get();
return view('pages.flags', ['resource' => $resources]);
}
public function addFlag($id)
{
$flag = Flagged::create(Request::all());
$resource = Resources::findOrFail($id);
$resource->update(array('Flagged' => 1));
$resource->flags()->attach([$flag->id]);
dd($resource::all());
return back();
}
//////// This function inserts only the Flagged table data into the Flagged table, It doesnt do what I want it to do, so i've commented it out/////
public function postFlag()
{
$flag = Flagged::create([
'Flag_Reason' => Input::get('reason'),
'Other_Comments' =>Input::get('comments')]);
$flag->save();
\Session::flash('flash_message', 'Flagged!');
return redirect('resource');
}
}
Resource View
...
#foreach($resources as $resource) #foreach ($resource->locations as $location)
<tr>
<td> <a class="btn btn-small btn-default" style="float:right; margin-right:5px;" href="{{ URL::to('resource/addToCart/' .$resource->Resource_ID) }}">+</a> {{ $resource->Name }}</td>
<td>{{ $resource->Description }}</td>
<td>{{ $location->Address }}</td>
<td>{{ $location->City }}</td>
<td>{{ $location->Zip_Code }}</td>
<td>{{ $location->County }}</td>
<td>
<button type="button" class=" msgBtn btn btn-default" style=" display:inline; margin-right:auto;">Edit
</button>
<button type="button" id="submitFlag" class=" msgBtn btn btn-default" style=" display:inline; margin-right:auto;">Flag
</button>
<button type="button" class=" msgBtn3 btn btn-default pull-right" style="display:inline; margin-right:auto;">Delete
</button>
</td>
</tr>
#endforeach
#endforeach
Modal, inside the Resources View
<div class="modal fade" id="flagResource" tabindex="-1" role="dialog" aria-labelledby="flagModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h4 class="modal-title"
id="flagResourceLabel" style="text-align:center;"> Flagged
</h4>
</div>
<div class="modal-body">
{!! Form::open(array('route'=>'resource', 'class'=>'form', 'method'=>'POST')) !!}
<div class="form-group">
<label for="reason" class="control-label">Reason for Flagging:</label>
{!! Form::text('reason', null, array('class'=> 'form-control', 'placeholder'=>'Reason')) !!}
</div>
<div class="form-group">
<label for="comments" class="control-label">Other Comments:</label>
{!! Form::text('comments', null, array('class'=> 'form-control', 'placeholder'=>'Comments')) !!}
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<span class="pull-right">
<button id="submitFlag" type="submit" class="btn btn-primary" style="margin-left:5px;">Flag</button>
</span>
</div>
{!! Form::close() !!}
</div>
</div>
</div>
<script>
$('#flagResource').on('show.bs.modal', function(e) {
//var submitFlag = $(e.relatedTarget);
var resourceName = $(e.relatedTarget).data('resource-name');
var resourceId = $(e.relatedTarget).data('resource-id');
var modal = $(this);
modal.find('.modal-title').text(resourceName);
});
</script>
The problem I think is happening is my form open inside my modal
{!! Form::open(array('route'=>'resource', 'class'=>'form', 'method'=>'POST')) !!}, and my addFlag function accepts an ID, but my resource route doesn't need an {id} on it.
If someone could take a look at my routes and help me debug it, it would be great. Thanks in advance.
You need to keep the route how you had it so it passes the Resource_ID but then you need to also pass it when you setup your form.
{!! Form::open(array('route'=>'resource' array('Resource_ID' => $yourId), 'class'=>'form', 'method'=>'POST')) !!}
Regarding your comment, and looking closer at your code, I think it might make sense to re-consider how this works.
You are passing multiple resources to this view so I think adding the resource id to the URL like I originally suggested is not the best idea because it needs to be dynamic depending on what resource was clicked on and the URL isn't the easiest thing to change via javascript.
I think a better solution would be to go back to using Form::open(array('route'=>'resource', 'class'=>'form', 'method'=>'POST')) !!}, then removing the /{Resource_ID} portion from your route and also removing the $id from public function addFlag() since we are no longer passing it via the URL.
Then in your form, add a hidden valid for resource_id
<input type="hidden" name="resource_id" id="resource_id" value="" />
Then you are already listening for the bootstrap show event and grabbing the right resource id, we just need to add it to the value.
$('#flagResource').on('show.bs.modal', function(e) {
//var submitFlag = $(e.relatedTarget);
var resourceName = $(e.relatedTarget).data('resource-name');
var resourceId = $(e.relatedTarget).data('resource-id');
var modal = $(this);
modal.find('.modal-title').text(resourceName);
$('#resource_id').val(resourceId);
});
No in your addFlag() method, you can grab the resource id via...
$id = \Input::get('resource_id');
Your addFlag function inside FlagsController accepts a parameter called $id the exception you are receiving is because you have forgotten to add the parameter to your route.
Route::post('resource', ['as' => 'resource', 'uses'=>'FlagsController#addFlag']);
Should Be
Route::post('resource/{id}', ['as' => 'resource', 'uses'=>'FlagsController#addFlag']);
I believe Laravel Route parameters are name specific which is why {Resource_ID} does not work.
You can read more about routing with parameters in Laravel here
As for your modal inside the resources view you need to also pass the parameter of the resource you're updating on the form
{!! Form::open(array('route'=>'resource', array('id' => $yourIdHere), 'class'=>'form', 'method'=>'POST')) !!}
Make sure to replace $yourIdHere with the resource you want to up.
Everything else appears to be in order.

Categories