Update injected model from route in Laravel - php

I am trying to update some values and it's creating a new one instead of updating the selected data
this is the controller code
public function update(Request $request, Payment_Student $payment_Student)
{
$payment_Student->date =request('date');
$payment_Student->amount =request('amount');
$payment_Student->formation_id =request('formation_id');
$payment_Student->student_id =request('student_id');
$payment_Student->save();
return redirect()->route('payment.index');
}
This is my route code
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/search','CategoryController#search');
Route::resource('/category','CategoryController');
Route::resource('/formation','FormationController');
Route::resource('/professor','ProfessorController');
Route::resource('/student','StudentController');
Route::resource('/classroom','ClassroomController');
Route::resource('/session','SessionController');
Route::resource('/payment','PaymentController');
Route::resource('/seance','SeanceController');
Route::resource('/paymentprof','PaymentProfessorController');
Route::resource('/paymentstudent','PaymentStudentController');
Route::resource('/presence','PresenceController');
Route::resource('/profile','ProfileController');
This is my balde view code
<form method="POST" enctype="multipart/form-data" action="{{route('paymentstudent.update',$payment_Student->id)}}" class="form-horizontal">
{{method_field('PATCH')}}
#csrf
Date:
<br/>
<input class="form-control" type="date" name="date">
<br/>
Amount:
<input type="number" value="{{$payment_Student->amount}}" name="amount"
class="form-control">
<br/>
Formation:
<select class="form-control" name="formation_id">
#foreach($formation as $formation)
<option value="{{$formation->id}}">{{$formation->name}}</option>
#endforeach
</select>
<br/>
Student:
<select class="form-control" name="student_id">
#foreach($student as $student)
<option value="{{$student->id}}">{{$student->lastname}}</option>
#endforeach
</select>
<div class="card-footer">
<button type="submit" class="btn btn-primary">Save Changes</button>
</div>
<br>
</form>
when I select a data to update it creates new data the updated value that I have inserted

By default when you make a resource laravel will singularize the resource name and make a variable out of it.
Example: Route::resource('videos', 'VideoController') laravel will expect the variable $video
In your case, paymentstudent will probably give the variable $paymentstudent
Fortunatly, you can customize your own parameter name
Route::resource('paymentstudent', 'PaymentStudentController', ['parameters' => [
'paymentstudent' => 'payment_Student'
]]);

Fetch the eloquent model from the one passed in the route and update accordingly, since you're using route resource, pass the actual object in the route by named parameter
<form method="POST" enctype="multipart/form-data" action="{{ route('paymentstudent.update', ['paymentstudent' => $payment_Student]) }}"
public function update(Payment_Student $payment_Student)
{
$payment_Student = Payment_Student::find($payment_Student->id);
$payment_Student->date = request('date');
$payment_Student->amount = request('amount');
$payment_Student->formation_id = request('formation_id');
$payment_Student->student_id = request('student_id');
$payment_Student->save();
return redirect()->route('payment.index');
}

Related

Laravel: How to get ID from Papers Table to Store in Bookmarks Table

I can't get the PaperID to store into my Bookmarks DB
here is my controller for the bookmark store function
public function store(Request $request)
{
$request->validate([
'BookmarkName' => 'required',
]);
$paper = DB::table('papers')
->where('PaperID', '=', $request->paper_id)
->value('PaperID');
$bm = new Bookmarks();
$bm->BookmarkName=$request->BookmarkName;
$bm->paper_id = $paper;
$bm->save();
return redirect()->back()->with('success','Bookmark Added');
}
here is the form to call the function
<form class="bookmarkInput" action="{{ route('Bookmarks')}} " method="POST" >
#csrf
<div class="group">
<input class="inputInfo" type="text" name="BookmarkName" required>
<span class="highlight"></span>
<span class="bar"></span>
<label class="infoLabel">Bookmark Name</label>
</div>
<br>
<br>
<button class="redBtn" type="submit">Add</button>
</form>
here is the route for it
Route::post('/Bookmarked', [App\Http\Controllers\BookmarkController::class, 'store'])->name('Bookmarks');
I do not know why it isn't getting the ID calling papers DB seems good but it doesn't want to get the current ID of the paper I want to bookmark
You are not passing paper_id from form.
That's why your ->where('PaperID', '=', $request->paper_id)
don't have value of paper_id.
you can pass paper_id from form by using hidden input field.
<input type="hidden" name="paper_id" value = {{ $paper_id }}>
Remember to pass paper_id variable containg paper_id value to the blade having form.
Also add ->first() before ->value('PaperID').

laravel route name parameter

Use a pageNation to request the value of the page to the controller. But why can't any parameters reach the controller?
Route::get('/index', 'Penpal\ViewController#index')->name('penpal.index');
<form action="{!! route('penpal.index', ['menu' => 'p11-c3']) !!}" method="get">
<select id="inputState" class="form-control" style="height:35px; width:80%" name="pagination" onchange="this.form.submit()">
<option value="3">#lang('penpal/component/indexMenu.twelve')</option>
<option value="4">#lang('penpal/component/indexMenu.twenty_four')</option>
<option value="5">#lang('penpal/component/indexMenu.thirty_six')</option>
</select>
</form>
public function index (Request $request){
return $request;\
}
A parameter named "menu" cannot be received from the controller.
Your <form> is using method='get', instead of method='POST' (which is used to post data to the request via a form.
You will also need to use #csrf in your blade template or you will not be able to post data:
<form action="{!! route('penpal.index', ['menu' => 'p11-c3']) !!}" method="POST">
#csrf
<select id="inputState" class="form-control" style="height:35px; width:80%" name="pagination" onchange="this.form.submit()">
<option value="3">#lang('penpal/component/indexMenu.twelve')</option>
<option value="4">#lang('penpal/component/indexMenu.twenty_four')</option>
<option value="5">#lang('penpal/component/indexMenu.thirty_six')</option>
</select>
</form>
Finally, make sure that your route is a ::post() route.
Use Post method both route and form
<form action="{!! route('penpal.index', ['menu' => 'p11-c3']) !!}" method="post">
Route::match(['get','post'],'/index', 'Penpal\ViewController#index')->name('penpal.index');
You haven't set any route parameters for your route and neither passing any to your controller method. And it would be a better idea to use POST then GET.
Change this to
Route::get('/index', 'Penpal\ViewController#index')->name('penpal.index');
this
Route::post('/index/{menu?}', 'Penpal\ViewController#index')->name('penpal.index');
and your form
<form action="{{ route('penpal.index', ['menu' => 'p11-c3']) }}" method="POST">
#csrf
And in your controller method you can fetch the passed parameter
public function index (Request $request, $menu){
print_r($menu);
}

Parameter goes into array as the name of the field instead of the value

What am I trying to achieve?
I have "tasks" and each task can have multiple "notes", so when you select a Task and click notes, it takes you to a page with all the notes for the task in which you clicked.
Each note has a field called "task_id", so my problem is passing this task_id to the note.
I'm trying to pass it like this on the notes form:
<form method="POST" action="{{route('notes.store',$task)}}">
#include('notes.form')
</form>
And it goes into my controller
public function store(Request $r)
{
$validatedData = $r->validate([
'note' => 'required',
]);
$r['created_by'] = Auth::user()->user_id;
return $r;
/*
$note = Note::create($r->all());
return redirect('/notes')->with('store');
*/
}
But I return it to see how its going and I get this:
{"_token":"OmGrbYeQDl35oRnmewrVraCT0SHMC16wE4gD56nl","note":"363","created_by":4,"8":null}
That 8 at the end is actually the correct task id, but it appears as the name instead of the value.
What may be causing this?
This is my form view:
#csrf
<div class="col">
<div class="form-group">
<input type="text" class="form-control" name="note">
</div>
</div>
<div class="col-10">
<div class="form-group">
<button class="btn btn-success" type="submit">Add note</button>
<br><br>
</div>
</div>
These are my routes:
Route::get('/tasks/{task}/notes', ['as' => 'tasks.notes', 'uses' => 'NoteController#index']);
Route::get('/projects/{project}/tasks', ['as' => 'projects.tasks', 'uses' => 'ProjectController#seeTasks']);
Route::get('/projects/results','ProjectController#filter');
Route::get('/tasks/results','TaskController#filter');
Route::resource('projects','ProjectController');
Route::resource('clients','ClientController');
Route::resource('tasks','TaskController');
Route::resource('users','UserController');
Route::resource('notes','NoteController');
You are trying to pass the task_id as a route parameter, but your notes.store route has no route parameters.
Verb Path Action Route Name
POST /notes store notes.store
Adding the task_id as a hidden input should properly send it with the request:
<form method="POST" action="{{ route('notes.store') }}">
<input type="hidden" name="task_id" value="{{ $task->id }}">
#include('notes.form')
</form>

Laravel form submission with url parameters

When the user accesses a certain brand page, I pull the information associated with that brand. Then the user has the chance to submit an application for this brand.
When the user submits the form, I want the form to post to /apply/brand/{brand_id} because I want to store this application in my application table with the brand_id as one of the fields (the other fields in this table comes from the fields in my form, but the brand_id will be an URL parameter)
The problem is that when I submit the form, the form posts to /apply/brand/undefined and the submission does not work correctly. I do not reach the ApplicationController#apply_store method.
EDIT:
To debug my problem, I printed out the {{$brand -> id }} right before the element and it printed out fine. However, when the form submits, it goes to /apply/brand/undefined instead of /apply/brand/{{$brand -> id }}. The $brand variable somehow becomes undefined inside of my form.
EDIT:
I hardcoded the from to submit to /apply/brand/43. When I press submit, the url shows up as /apply/brand/43 at first but then quickly changes to /apply/brand/undefined before redirecting me to my default page.
Controller Method for Accessing a Brand Page
public function brandProfile(){
$brand = Brand::where('user_id', Auth::user()->id)->first();
$industry = Industry::where('status', 1)->get();
return view('new-design.pages.profile_brand')
->withData($brand)
->withIndustry($industry);
}
Brand Application Form
<form id="application_form" method="post" action="/apply/brand/{{ $data -> id }}" enctype="multipart/form-data">
{{ csrf_field() }}
<ul>
<div class="col-md-6">
<li>
<label>First Name</label>
<input type="text" class="form-control" name="firstname" placeholder="First Name"/>
</li>
</div>
<div class="col-md-6">
<li>
<label>Last Name</label>
<input type="text" class="form-control" name="lastname" placeholder="Last Name"/>
</li>
</div>
<div class="col-md-6">
<li>
<label>Email</label>
<input type="email" class="form-control" name="email" placeholder="Email"/>
</li>
</div>
<div class="col-md-6">
<li>
<label>Instagram Handle</label>
<input type="text" class="form-control" name="instagram" placeholder="Instagram Handle"/>
</li>
</div>
<li>
<label>Cover Letter</label>
<p>Please write your message in the space below, or attach a file (-list of file types accepted-)</p>
<textarea cols="30" rows="50" name="message" class="textarea"></textarea>
</li>
<li>
<div class="upload-cover-letter">
<i class="fa fa-paperclip" style="cursor:pointer;font-size:20px;"></i>
<input type="file" name="file" id="myFileDocument" class="inputfile inputfile-1"/>
<label for="myFileDocument" id="myFileDoc"><span>Choose File</span></label>
<span style="font-size: 12px">No File Chosen</span>
<span class='hidden_text' style="font-size: 12px">Upload File (Max 2MB)</span>
</div>
<input type="hidden" id="myFileName" name="file_name" />
</li>
</ul>
<div class="btn-center">
<button type="button" class="btn btn-gradient waves-effect" id="create_campaign">Apply Now</button>
</div>
</form>
Route in web.php
Route::post('/apply/brand/{brand_id}', 'ApplicationController#apply_store');
Store application in database
public function apply_store(Request $request)
{
$application = new Application([
'influencer_id' => Auth::id(),
'brand_id' => $request->get('brand_id'),
'message' => $request->get('message'),
'status' => 'applied'
]);
$application->save();
// TODO: add helper message to confirm application did return
return redirect('/apply');
}
In your controoler metohd apply_store, you need to put the variable that will receive the variable sended by url parameter.
public function apply_store(Request $request, $brand_id){}
I typically work with compact or with to send the param to the blade view. So:
return view('new-design.pages.profile_brand', compact('brand'));
or without compact:
return view('new-design.pages.profile_brand')->with('brand', $brand)
I haven't seen the withVar that you are attempting above (doesn't mean it doesn't exist though). Try with compact and dump $brand on the view to make sure its coming through with data (not undefined). If that dumps successfully, but still fails, you may want to try adding the variable outside the quotes or totally within the blade {{}} in the form like:
<form id="application_form" method="post" action={{ "/apply/brand/".$brand-> id }} enctype="multipart/form-data">
Not sure about how the action is getting though like you have in your code above, though - you might wish to use the url() method:
<form id="application_form" method="post" action={{ url("/apply/brand/".$brand-> id) }} enctype="multipart/form-data">
change your method like this
public function apply_store(Request $request,$brand_id)
{
$application = new Application([
'influencer_id' => Auth::id(),
'brand_id' => $rbrand_id,
'message' => $request->get('message'),
'status' => 'applied'
]);
$application->save();
// Ngentod lah kalian semua, anjeng
return redirect('/apply');
}

how to update database using laravel controller? MethodNotAllowedHttpException No message error message

I'm trying to update my database using a form on my
edit.blade.php page as shown below. The edit part works correctly as the fields are filled in in the form as expected, however when i try to save, an error message of
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
is displayed. I have tried so many ways on how to fix it and I'm not sure where I'm going wrong. Hopefully it's something simple to fix?
edit.blade.php
#extends('layouts.app')
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<form method="post" action="{{ action('PostsController#update', $id) }}">
{{ csrf_field() }}
<input type="hidden" name="_method" value="PATCH" />
<h1>Edit Item</h1>
<div class="form-group">
<label for="item">Item:</label>
<input type="text" id="item" name="item" value="{{$post->item}}" class="form-control" required>
</div>
<div class="form-group">
<label for="weight">Weight (g):</label>
<input type="number" id="weight" value="{{$post->weight}}" name="weight" class="form-control">
</div>
<div class="form-group">
<label for="noofservings">No of Servings:</label>
<input type="number" id="noofservings" value="{{$post->noofservings}}" name="noofservings" class="form-control">
</div>
<div class="form-group">
<label for="calories">Calories (kcal):</label>
<input type="number" id="calories" name="calories" value="{{$post->calories}}" class="form-control">
</div>
<div class="form-group">
<label for="fat">Fat (g):</label>
<input type="number" id="fat" name="fat" value="{{$post->fat}}" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>
</div>
</div>
#endsection
PostsController.php
<?php
public function update(Request $request, $id)
{
$this->validate('$request', [
'item' => 'required'
]);
$post = Post::find($id);
$post->item = $request->input('item');
$post->weight = $request->input('weight');
$post->noofservings = $request->input('noofservings');
$post->calories = $request->input('calories');
$post->fat = $request->input('fat');
$post->save();
return redirect('/foodlog');
}
web.php
<?php
Route::get('edit/{id}', 'PostsController#edit');
Route::put('/edit', 'PostsController#update');
Post.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'id',
'user_id',
'item',
'weight',
'noofservings',
'calories',
'fat',
'created_at'
];
}
My website is a food log application and this function is so that they can edit their log.
Any help is greatly appreciated!
Based on Michael Czechowski I edited my answer to make this answer better, The main problem is inside your routes:
Route::put('/edit/{id}', 'PostsController#update');
You have to add the id inside your route parameters either. Your update() function needs two parameters, first the form parameters from the formular and second the $id of the edited log entry.
The second problem is , the form method field is 'patch' and your route method is 'put'.
The difference between 'patch' and 'put' is:
put: gets the data and update the row and makes a new row in the database from the data that you want to update.
patch: just updates the row and it does not make a new row.
so if you want to just update the old row change the route method to patch.
or if you really want to put the data, just change the put method field in your form.
simply by : {{method_field('PUT')}}
Remember, the form's and the route's methods must be same. If the form's method is put, the route method must be put; and vice-versa.
The main problem is inside your routes:
Route::put('/edit/{id}', 'PostsController#update');
You have to add the id inside your route parameters either. Your update() function needs two parameters, first the form parameters from the formular and second the $id of the edited log entry.
The second one is inside your HTML template:
<input type="hidden" name="_method" value="PUT" />
To hit the right route you have to add the corresponding method to your route Route::put('/edit/{id}', 'PostsController#update');.
A possible last problem
<form method="post" action="{{ action('PostsController#update', $post->id) }}">
I am not sure how your template works, but $id is possible not set inside your template. Maybe try to specify the ID depending on your post. Just to make it sure the ID comes from the shown post.
Further suggestions
Best practice is to use the symfony built-in FormBuilder. This would make it easier to target those special requests like PUT, PATCH, OPTIONS, DELETE etc.

Categories