Im new in Laravel and i dont understand how to make action forms and routing for editing post
Here is my routes --
Route::post('/menu', 'MenuController#store');
Route::resource('/menu', 'MenuController');
here is controller --
public function update(Request $request, $id)
{
$this->validate($request, [
'menuName' => 'required',
'menuLink' => 'required'
]);
//create new menu
return $id;
// $menus->name = $request->input('menuName');
//$menus->link = $request->input('menuLink');
//$menus->save();
//return redirect('/menu')->with('success', 'Menu updated');
}
Return $id is for check what "id" will give me and he gives me this- "{id}"
here is form --
<form action = "/menu/{id}" method = "POST">
{{ csrf_field() }}
<input name = "_method" type = "hidden" value = "PUT">
<input type="text" id="menuName" name="menuName" class="input-block-level" placeholder="Menu name">
<input type="text" id="linkName" name="menuLink" class="input-block-level" placeholder="Menu link ">
<button type="submit" class="btn btn-success pull-right">Submit</button>
</form>
i am really messed up allready and dont know what i am doing wrong. I cant understand why update funtion returns me "{id}" not value of ID and how can i make this all works
Your are not passing id in your view , you are passing it as a string , u need it create a variable and set it to the right id and pass it to your form.
Change your form action from
action = "/menu/{id}"
to
action = "/menu/".$id"
or you can use laravel blade
Form::open(['route' => ['menu.update', $id]])
and don't forget to close the form at the end
{!!Form::close!!}
You did something wrong with the action attribute. Change it to:
action="/menu/{{ $id }}"
Okay,
you have an edit method which will show the form, that method should return the menu object
public function update($id)
{
// get the menu you wan to edit
$menu = Menu::find($id);
// return the form with the menu object
return view('your.form.view', compact('menu'));
}
Now the form should be like this
// use that object u returned in the form action
<form action = "/menu/{{ $menu->id }}" method = "POST">
{{ csrf_field() }}
<input name = "_method" type = "hidden" value = "PUT">
<input type="text" id="menuName" name="menuName" class="input-block-level" placeholder="Menu name">
<input type="text" id="linkName" name="menuLink" class="input-block-level" placeholder="Menu link ">
<button type="submit" class="btn btn-success pull-right">Submit</button>
</form>
Now the update method should be something like this
public function update(Request $request, $id)
{
$this->validate($request, [
'menuName' => 'required',
'menuLink' => 'required'
]);
// update the data
$bool = Menu::where('id',$id)->update([
'menuName'=> $request->menuName,
'menuLink'=> $request->menuLink,
]);
if(!$bool){
Session::flash('alert','error');
return view('page.index');
}
Session::flash('alert','success');
return view('page.index');
}
This first method is "get" edit that should show the form,
the second is put update that should receive the data from the form(after the show method) and use i to update.
I resolved the error ---
in update blade befor form i added foreach
<div class="container">
<div class="row">
#foreach($menus as $menus)
<form action="/menu/{{$menus->id}}" method="POST">
#endforeach
{{ csrf_field() }}
<input name = "_method" type = "hidden" value = "PUT">
<input type="text" id="menuName" name="menuName" class="input-block-level" placeholder="Menu name">
<input type="text" id="linkName" name="menuLink" class="input-block-level" placeholder="Menu link ">
<button type="submit" class="btn btn-success pull-right">Submit</button>
</form>
</div>
</div>
But now he is editing only 1st post and no matter wich post edit im switching
here is controller --
public function edit($id)
{
$menus = Menu::all();
return view('admin.editmenu')->with('menus', $menus);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'menuName' => 'required',
'menuLink' => 'required'
]);
//create new menu
$menus = Menu::find($id);
$menus->name = $request->input('menuName');
$menus->link = $request->input('menuLink');
$menus->save();
return redirect('/menu')->with('success', 'Menu updated');
}
menu list blade ---
#if(count($menus) > 1)
#foreach($menus as $menus)
<tr>
<th scope="row">1</th>
<td>{{$menus->name}}</td>
<td>{{$menus->link}}</td>
<td>{{$menus->created_at}}</td>
<td>{{$menus->updated_at}}</td>
<td>
<button type = "button"class = "btn btn-outline-danger btn-sm">Delete</button>
<a href = "/menu/{{$menus->id}}/edit" class = "btn btn-outline-warning btn-sm">Edit</button>
</td>
</tr>
#endforeach
#else
Ok ive got it and resolved.
I will start with routes
routes----------
Route::resource('menu', 'MenuController');
that post route was unnecessary, but that didnt affect anything
controller -------
public function edit($id)
{
$menus = Menu::find($id);
return view('admin.editmenu')->with('menus', $menus);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'menuName' => 'required',
'menuLink' => 'required'
]);
//create new menu
$menus = Menu::find($id);
$menus->name = $request->input('menuName');
$menus->link = $request->input('menuLink');
$menus->save();
return redirect('/menu')->with('success', 'Menu updated');
}
Where in edit function i must find ID witch needs to be editing
menu list -----------------
#if(count($menus) > 1)
#foreach($menus as $menu)
<tr>
<th scope="row">1</th>
<td>{{$menu->name}}</td>
<td>{{$menu->link}}</td>
<td>{{$menu->created_at}}</td>
<td>{{$menu->updated_at}}</td>
<td>
<button type = "button"class = "btn btn-outline-danger btn-sm">Delete</button>
<a href = "/menu/{{$menu->id}}/edit" class = "btn btn-outline-warning btn-sm">Edit</button>
</td>
</tr>
#endforeach
#else
<p class = "well"> No menu items created!</p>
#endif
I only changed $menus as $menus on "$menus as $menu" to be clear.
edit blade ------------
#extends('admin.main')
#section('content')
<div class="container">
<div class="row">
<form action="/menu/{{$menus->id}}" method="POST">
{{ csrf_field() }}
<input name = "_method" type = "hidden" value = "PUT">
<input type="text" id="menuName" name="menuName" class="input-block-level" placeholder="Menu name" value="{{ $menus->name }}">
<input type="text" id="linkName" name="menuLink" class="input-block-level" placeholder="Menu link " value="{{ $menus->link }}">
<button type="submit" class="btn btn-success pull-right">Submit</button>
</form>
</div>
</div>
#endsection
Here i deleted #foreach like #Snapey told and added the value option.
I guess value option gave me the errrors all the time.
Thank you all for attention and willing to help! Hope that someday i could help others with my knowledge.
Related
I am getting an error which says
"Property [id] does not exist on this collection instance. (View: C:\newXampp\htdocs\testUser\resources\views\Stock\edit.blade.php)"
This is my Controller
public function editStock(Stock $id)
{
//
$Stock = Stock::find($id);
return view('Stock.edit', compact('Stock', 'id'));
// return response($stock);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Stock $stock
* #return \Illuminate\Http\Response
*/
public function updateStock(Request $request, $id)
{
$request->validate([
'id'=>'required',
'stock_name'=>'required',
'stock_qty'=>'required',
'stock_unit'=>'required',
'stock_price_per_kg'=>'required',
'stock_weight_per_qty'=>'required'
]);
$stock = Stock::find($id);
$stock->stock_name = $request->get('stock_name');
$stock->stock_qty = $request->get('stock_qty');
$stock->stock_unit = $request->get('stock_unit');
$stock->stock_price_per_kg = $request->get('stock_price_per_kg');
$stock->stock_weight_per_qty = $request->get('stock_weight_per_qty');
$stock->save();
return redirect('/Stock/index/')->with('success', 'Stock updated!');
}
These are my routes
//Route for Stock
Route::get('/Stock/createStock/', 'ChicController#createStock')->name('createStock');
Route::post('/Stock/createStock/', 'ChicController#storeStock')->name('storeStock');
Route::get('/Stock/index/', 'ChicController#indexStock')->name('indexStock');
Route::get('/Stock/edit/{id}', 'ChicController#editStock')->name('editStock');
Route::post('/Stock/edit/{id}', 'ChicController#updateStock')->name('updateStock');
Route::delete('/Stock/index/{id}', 'ChicController#destroyStock')->name('deleteStock');
This is my edit.blade.php
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-sm-8 offset-sm-2">
<h1 class="display-3">Update a Stock</h1>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
<br />
#endif
<form method="post" action="{{ route('updateStock', $Stock->id) }}">
{{ csrf_field() }}
<div class="form-group">
<label for="stock_name">Stock Name:</label>
<input type="text" class="form-control" name="stock_name" value={{$Stock->stock_name }} />
</div>
<div class="form-group">
<label for="stock_qty">Stock Amount:</label>
<input type="number" class="form-control" name="stock_qty" value={{$Stock->stock_qty }} />
</div>
<div class="form-group">
<label for="stock_unit">Stock Unit:</label>
<select id="stock_unit" name="stock_unit" value={{$Stock->stock_unit}}>
<option value="Kg">Kg</option>
<option value="Qty">Qty</option>
</select>
</div>
<div class="form-group">
<label for="stock_price_per_kg">Price Per Kg:</label>
<input type="number" class="form-control" name="stock_price_per_kg" value={{$Stock->stock_price_per_kg }} />
</div>
<div class="form-group">
<label for="stock_weight_per_qty">Weight Per Qty:</label>
<input type="number" class="form-control" name="stock_weight_per_qty" value={{$Stock->stock_weight_per_qty }} />
</div>
<button type="submit" class="btn btn-primary">Update</button>
</form>
</div>
</div>
#endsection
I have tried everything, but I could not solve the problem. When I try to echo the $id in the edit Controller, it shows the correct $id. Hence, I do not know how to solve this, nor do I know why this is happening.
For your editStock method you are already receiving an instance of a Stock model matching the id from the route parameter due to the Implicit Route Model Binding that is taking place. When you pass that $id variable to Stock::find($id) you are passing a Model which is Arrayable. This causes find to become findMany thinking you are passing many ids. You end up with a Collection because of this:
public function editStock(Stock $id)
{
$Stock = Stock::find($id);
return view('Stock.edit', compact('Stock', 'id'));
}
$Stock is a Collection because of passing many to find. I would adjust this to only pass the $id variable to your view which is the Stock that you want.
public function editStock(Stock $id)
{
return view('Stock.edit', [
'Stock' => $id,
]);
}
Your view will now have a Stock variable which is the Stock that you wanted.
Laravel 5.8 Docs - Routing - Route Model Bindings - Implicit Bindings
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');
}
This is my route :
Route::post('/store', 'EditlinkController#store');
My controller
public function index()
{
$id = $_GET['id'];
$links = DB::table('slugs')->where('slugs.id',$id)
->join('links','links.sid','=','slugs.id')
->get();
return view('editlink', ['links' => $links]);
}
public function store(Request $request, $id)
{
$url = $request->input('url');
$data =new link;
$sid = $id;
$data->sid = $sid;
$data ->url = $url;
$data ->save();
return redirect('/links');
}
And my view:
<form role="form" method='POST' action="{{url('store')}}">
<div class="entry input-group col-xs-3">
<input class="form-control" name="url" type='url' placeholder="https://..." size="100"/>
<input type="hidden" name="_Token" value="{{ csrf_token() }}">
<button type="submit" class="btn btn-primary" type="button">
<span class="material-icons md-12">add</span>
</button>
{{ csrf_field() }}
</div>
</form>
So basically here I want to call $id from index to store. I also have tried
Route::post('/store/{id}', 'EditlinkController#store');
But still doesn't work. Thank you.
Your route, /store/{id}, requires you to have a route parameter. Make sure you have an $id available to you before you generate your url for your form.
An example of what your open form tag should look like with the $id included:
<form role="form" method='POST' action="{{url('store', $id)}}">
I'm assuming the view editlink is where the markup for the form resides. If so, then you can simply pass the value of the id to your view from your controller:
return view('editlink', ['links' => $links, 'id' => $id]);
I am using PHP Laravel framework. I am trying to save a form after submission. Strangely first time it is not saving, but subsequently, it is saving. On the first post request, the flow isn't even entering function save_application
Code below.
My controller:
class ApplicationController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth',['except' => ['store_application']]);
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function save_application(Request $request){
$user = Auth::user();
if(isset($request->application)){
$application = Application::where("user_id",$user->id)->first();
if($application){
$application->update($request->application);
}else{
$application = new Application;
$application = Application::create($request->application);
$application->user_id = $user->id;
$application->save();
}
}
return $this->store_application($request);
}
public function store_application(Request $request){
if(isset($request->application)){
if($request->session()->has('application')){
$request->session()->forget('application');
}
$application_data = [];
$application = new Application;
$application->attributes = $request->application;
$application_data["application"] = $application;
$request->session()->put("application" , $application_data);
}
//
return Redirect::to("/application")->withErrors(array("success"=>"Thank you for submitting the application"));
}
}
My routers
Route::post('/application', 'ApplicationController#save_application')->name('application');
Route::post('/application_store', 'ApplicationController#store_application')->name('application');
My html
<form method="POST" action="/application" enctype="multipart/form-data" id='application_form'>
<input type="hidden" name="_token" value="xtQapusSjgf5XVUxjCOudedeH93a8hEqyfaNh8ChEaKt">
<input type='checkbox'>
<label>I've read and accept the terms and conditions</label>
<p class='font-size-16 font-bold text-uppercase text-black'>
Your information
</p>
<hr class='hr1'>
<div class='row form-group'>
<div class='col-lg-6'>
<label class='control-label'>First name*</label>
<input type='text' class='form-control' name='application[first_name]' value="">
</div>
<div class='col-lg-6'>
<label class='control-label' >Last name*</label>
<input type='text' class='form-control' name='application[last_name]' value="">
</div>
</div>
<div class='form-group'>
<label class='control-label' >Middle name</label>
<input type='text' class='form-control' name='application[middle_name]' value="">
</div>
<div class='form-group'>
<label class='control-label'>ID*</label>
<input type='text' class='form-control' name='application[]' value="">
</div>
<button class="btn btn-primary text-uppercase">Submit <i class='fa fa-check text-white'></i></button>
</form>
your routes have the same name, give them differents.
Route::post('/application', 'ApplicationController#save_application')->name('application');
Route::post('/application_store', 'ApplicationController#store_application')->name('other');
and in your form, you can:
<form method="POST" action="{{ route('application') }}" enctype="multipart/form-data" id='application_form'>
and as senty say:
<button type="submit">
</form>
I think you overcomplicate things, you can simply use updateOrCreate() to make it cleaner.
First of all, make sure $fillable or $guarded is utilized in your Application model. (Application.php)
protected $fillable = ['each', 'field', 'as', 'string'];
// or
protected $guarded = [];
Some improvements for your method:
public function save_application(Request $request){
// 1. Do a proper check
$request->validate([
'application.first_name' => 'required',
'application.middle_name' => 'required',
'application.last_name' => 'required'
]);
// 2. Update or Create
$application->updateOrCreate(
[ 'user_id' => $user->id ],
$request->application // I suppose this is an array that you want
);
// 3. Handle the redirect the right way so you can eliminate the other `store_applcation()` method entirely
return redirect()->back()->with([
'application' => $application
'success' => "Your Message"
]);
}
Also you don't need store_application() method in your controller or its route because your html form is POST'ing to /application route.
This is what you want, right?
Im Trying to update my table through Laravel Updation,i get no error when i tried to print the result i just got an null value ,i have pasted my model and controller.
controller
public function update_FAQ_submit()
{
$data = Input::except(array(
'_token'
));
$rule = array(
'faq_ques' => 'required',
'faq_ans' => 'required'
);
$id = Input::get('id');
$validator = Validator::make($data, $rule);
if ($validator->fails()) {
return Redirect::to('Coin_lion/FAQ')->withErrors($validator->messages())->withInput();
} else {
$entry = array(
'faq_ques' => Input::get('faq_ques'),
'faq_ans' => Input::get('faq_ans')
);
$faq=FAQ::update_faq($id, $entry);
return Redirect::to('Coin_lion/manage_FAQ');
}
}
Model
public static function update_faq($id, $entry)
{
return DB::table('faq')->where('id', '=', $id)->update($entry);
}
Routes:
Route::post('Coin_lion/update_FAQ_submit','AdminController#update_FAQ_submit');
my DB
My form
here is my form ,i have included what method i used previously
">
{!! Form::hidden('id', $id) !!}
#foreach ($faq as $info)
<label>Enter your question:</label><br>
<input type="text" class="form-control" name="faq_ques" value="<?php echo $info->faq_ques ?>"><br>
<label>Enter your Answer:</label>
<textarea class="form-control" name="faq_ans" cols="10" rows="5" ><?php echo $info->faq_ans ?></textarea>
<input type="submit" class="btn btn-success" name="submit" value="ADD">
<input type="reset" class="btn btn-danger" name="submit" value="Cancel">
#endforeach
</body>
First try to check that you are getting values in your controller and passing it correctly in you model then you need to replace your query with this. And replace your model code with this.
public function update_faq($id, $entry)
{
DB::table('faq')->where('id',$id)->update($entry);
}
public static function update_faq($id, $entry) {
DB::table('faq')
->where('id', $id) // find your faq by their id
->update($entry); // update the record in the DB.
}