Perform specific action on button in Bootstrap modal (Laravel) - php

I created a modal which displays information specific to their id entries and placed the Approve and Reject button as below.
Screenshot of modal
When a user click on "Accept" or "Reject", it needs to pass id related to the viewed entries so the user can perform the requested action, whether to accept or reject the entries (default status is 'pending').
vendor.blade.php
<div class="modal-footer">
<span class="pull-left">
<form method="POST" action="{{ route('approve') }}">
#method('PUT')
#csrf
<button type="submit" class="btn btn-success">Approve</button>
</form>
</span>
<span class="pull-right">
<form method="POST" action="{{ route('reject') }}">
#method('PUT')
#csrf
<button type="submit" class="btn btn-danger">Reject</button>
</form>
</span>
</div>
In VendorController.php
public function index()
{
$vendors = DB::select('select company_name, roc_no, created_at from mides_vendors');
$vendor_id = Vendor::where('status', 'Pending');
return view('panel.vendor', ['vendors' => $vendors]);
}
ApprovedVendorController.php
<?php
namespace App\Http\Controllers;
use App\User;
use App\Vendor;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class ApproveVendorController extends Controller
{
public function approve(Request $request, $id)
{
DB::insert('insert into mides_users(name, email, password) select name,roc_no,password from mides_vendors where id = :id', ['id' => $id]);
DB::update('update mides_vendors set status = :status where id = :id', ['status' => 'Approved', 'id' => $id]);
return redirect('/');
}
public function reject(Request $request, $id)
{
DB::update('update mides_vendors set status = :status where id = :id', ['status' => 'Rejected', 'id' => $id]);
return redirect('/');
}
}
routes/web.php
Route::prefix('/panel')->group(function () {
Route::get('/dashboard', function () {
return view('panel.dashboard');
});
/* These routes only display the information/modal
Route::get('/approve-vendor', 'VendorController#showNewRegistration'); // return vendor.blade.php
Route::get('/vendor-approved', 'VendorController#showApproved'); // return vendor-approve.blade.php
Route::get('/vendor-reject', 'VendorController#showRejected'); // return vendor-reject.blade.php
/* These route used to perform the specific action */
Route::put('/approve/{id}', 'ApproveVendorController#approve')->name('approve');
Route::put('/reject{id}', 'ApproveVendorController#reject')->name('reject');
});
However, it returns this error.
Error got after clicking Accept or Reject
How do I pass the id of data? I tried as shown in pass the database value to modal popup to create the modal using second answer option (besides the ajax ones). Do I need to create another controller for these?
Edited: after do as explained by #Wreigh, it works, means that the status changed from 'pending' to 'accept/reject'. But, when I return to the previous page, which is the /panel/approve-vendor (the page is used for showing the pending list modal) then I got the error undefined variable vendorId.

You can provide the id via the url, or you can also use post values. However, let's try via the url as a parameter.
Update your routes to be like these:
Route::put('/approve/{id}', 'ApproveVendorController#approve')->name('approve');
Route::put('/reject/{id}', 'ApproveVendorController#reject')->name('reject');
Then in your form:
<form method="POST" action="{{ route('approve', $vendorId) }}">
<form method="POST" action="{{ route('reject', $vendorId) }}">
If you want via post values.
There's no need to update your routes, but update your controller action signatures:
public function approve(Request $request) {
$id = $request->input('id');
}
public function reject(Request $request) {
$id = $request->input('id');
}
And then insert this in your form:
<input type="hidden" name="id" value="{{ $vendorId }}">
WHY DO YOU ENCOUNTER THE ERROR?
In your function signature, you are expecting an $id parameter, which in your route definition, you do not have. Laravel cannot provide it magically like that, you have to provide it via the url, as a parameter.

since your approve route is like this /approve/{id} you cannot go to panel/approve because your are not passing the id
so try this:
vendor.blade.php (remove put and your id as hidden input)
<div class="modal-footer">
<span class="pull-left">
<form method="POST" action="{{ route('approve') }}">
<input type="hidden" name="id" value="{{ $id}}">
#csrf
<button type="submit" class="btn btn-success">Approve</button>
</form>
</span>
<span class="pull-right">
<form method="POST" action="{{ route('reject') }}">
#csrf
<input type="hidden" name="id" value="{{ $id}}">
<button type="submit" class="btn btn-danger">Reject</button>
</form>
</span>
</div>
ApprovedVendorController.php (remove all the parameters)
<?php
namespace App\Http\Controllers;
use App\User;
use App\Vendor;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class ApproveVendorController extends Controller
{
public function approve()
{
$id = request('id');
DB::insert('insert into mides_users(name, email, password) select name,roc_no,password from mides_vendors where id = :id', ['id' => $id]);
DB::update('update mides_vendors set status = :status where id = :id', ['status' => 'Approved', 'id' => $id]);
return redirect('/');
}
public function reject()
{
$id = request('id');
DB::update('update mides_vendors set status = :status where id = :id', ['status' => 'Rejected', 'id' => $id]);
return redirect('/');
}
}
routes/web.php (remove parameters)
Route::prefix('/panel')->group(function () {
Route::get('/dashboard', function () {
return view('panel.dashboard');
});
/* These routes only display the information/modal
Route::get('/approve-vendor', 'VendorController#showNewRegistration'); // return vendor.blade.php
Route::get('/vendor-approved', 'VendorController#showApproved'); // return vendor-approve.blade.php
Route::get('/vendor-reject', 'VendorController#showRejected'); // return vendor-reject.blade.php
/* These route used to perform the specific action */
Route::put('/approve', 'ApproveVendorController#approve')->name('approve');
Route::put('/reject', 'ApproveVendorController#reject')->name('reject');
});

Related

Laravel - Too Few Arguements

I'm trying to setup a simple button to update a db column value when clicked. I can't seem to figure out why my route isn't getting passed my value however?
HTML:
<form method="post" action="{{ route('approveResturant') }}">
{{ csrf_field() }}
<input type="hidden" name="id" value="{{ $resturant->id }}" />
<button class="btn btn-outline-success" type="submit">
Approve
</button>
</form>
Controller:
public function approveResturant($request)
{
dd($request->all());
$id = $request->id;
$resturant = Resturant::find($id);
$resturant->approved = 1;
$resturant->save;
return redirect()->back()->with('message', 'Resturant Approved Successfully!');
}
Route:
Route::post('approveResturant'[ResturantController::class,'approveResturant'])->middleware(['auth'])->name('approveResturant');
And finally, the error itself:
Any help appreciated!
Add the Request type-hint to your function:
use Illuminate\Http\Request;
public function approveResturant(Request $request)
{
dd($request->all());
$id = $request->id;
$resturant = Resturant::find($id);
$resturant->approved = 1;
$resturant->save;
return redirect()->back()->with('message', 'Resturant Approved Successfully!');
}
The difference here is that Laravel understands the Request type-hint and knows that it should inject the Request object from the pre-defined services it has in its service container. Otherwise, Laravel doesn't know where that parameter is coming from so assumes you will provide it. Simply naming your parameter $request is insufficient.
Update
Do you know why the function would still not be saving the new approved value to the DB?
A few potential reasons:
You have not removed the dd($request->all()); statement
$resturant = Resturant::find($id); failed to find a record in the database
save is a function not a property so $resturant->save; should be $resturant->save();
To isolate the exact issue you will need to perform some debugging (e.g. either using xdebug or dd statements).
Use Request Class
use Illuminate\Http\Request;
public function approveResturant(Request $request)
{
dd($request->all());
$id = $request->id;
$resturant = Resturant::find($id);
$resturant->approved = 1;
$resturant->save;
return redirect()->back()->with('message', 'Resturant Approved Successfully!');
}
<form method="post" action="{{ route('restaurant.approveResturant') }}">
{{ csrf_field() }}
<input type="hidden" name="id" value="{{ $resturant->id }}" />
<button class="btn btn-outline-success" type="submit">
Approve
</button>
</form>
Route::post("/restaurant/store", [RestaurantController::class, "approveResturant"])->name("restaurant.approveResturant");
use Illuminate\Http\Request;
public function approveResturant(Request $request)
{
$restaurant = Restaurant::where("id", $request->input("id"))->update([
"approved" => 1
]);
return redirect()->back()->with('message', 'Restaurant Approved Successfully!');
}

Can't update in database data. Laravel

I have a small problem with my Controller action. I can't update my "link" in Database, bt dd method work is correctly when I'm try to check data.
Form
<form class="col-lg-push-6" action="/admin/links/{{$link->id}}/update" method="POST">
#csrf
<div class="form-group bmd-form-group">
<label class="bmd-label-floating">New Link Value</label>
<input type="text" class="form-control" size="100" name="value">
<button class="btn btn-primary" type="submit">Update</button>
</div>
</form>
Controller
public function update(Request $request, $id)
{
$this->validate($request, [
'value' => 'required'
]);
$link=RedirectUrl::AllLinks()->where('id', $id);
$link->value = $request->input('value');
return redirect()->back()->with('message', 'Link Updated!');
}
Model
public function scopeAllLinks($query){
return $query->get();
}
Route
Route::prefix('admin')->middleware('auth')->group(function(){
Route::get('/', 'Admin\IndexController#index');
Route::get('dashboard', 'Admin\IndexController#index')->name('dashboard');
Route::get('links', 'Admin\LinkController#index')->name('links');
Route::get('links/{id}', 'Admin\LinkController#linkById');
Route::post('links/{id}/update', 'Admin\LinkController#update');
});
Few things here:
Your scopeAllLinks scope is incorrect, you don't call get inside a scope, instead you return the query builder instance.
You can use find since you're passing in a record id:
$link = RedirectUrl::find($id);
You never call save or update on the record:
$link->value = $request->input('value');
$link->save(); // <--- add this

Inserting data to database laravel

At the moment I am working with Laravel. I am trying to insert data into a database. It is not user data, but product data. Costumers have to be able to insert a title, description and price of a product into the database.
I have looked at the laravel website, however, I was unable to find anything. There are some people with the same question as mine on StackOverflow. However, the answers that were given to them do not work for me.
My controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProductsController extends Controller
{
public function insertform(){
return view('home');
}
public function insert(Request $request){
$productname = $request->input('title');
$description = $request->input('description');
$price = $request->input('price');
$data=array('title'=>$productname,"description"=>$description,"price"=>$price);
DB::table('products')->insert($data);
echo "Record inserted successfully.<br/>";
echo 'Click Here to go back.';
}
}
My view:
#section('content')
<h1>Add your new items here:</h1>
<form method="get">
<div class="title">
<div class="title">
<span class="input-group-text" id="title">Title</span>
</div>
<input type="text" name="title" class="form-control" aria-label="title" aria-describedby="inputGroup-sizing-default">
</div>
<br>
<br>
<div class="description">
<div class="description">
<span class="input-group-text" id="description">Description</span>
</div>
<input type="text" name="description" class="form-control" aria-label="description" aria-describedby="inputGroup-sizing-default">
</div>
<br>
<br>
<div class="price">
<div class="price">
<span class="input-group-text" id="price">Price</span>
</div>
<input type="text" name="price" class="form-control" aria-label="price" aria-describedby="inputGroup-sizing-default">
</div>
<br>
<br>
<div class="form-group">
<label for="exampleFormControlFile1">Insert Image</label>
<input type="file" class="form-control-file" id="exampleFormControlFile1">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
#endsection
My web.php:
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('insert','ProductsController#insertform');
Route::post('create','ProductsController#insert');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
My database structure:
The home and welcome, along with some code in the web.php, has been made by authentication.
Hopefuly you guys can help me out. I want to make sure that the product data is inserted into the database.
Don't use DB class. Instead create a model called Product and use model function to create or update data into table.
php artisan make:model Product
$product= Product::create([
'name' => $request->name, # declared as fillable on Product model
'description' => $request->description,
...
]);
Convert the route of /insert into POST and add csrf field in your form
#csrf
OR
<input type="hidden" name="_token" value="{{csrf_token()}}">
On your controller validation of input in insert function.
Also take a look at these -
https://laravel.com/docs/5.8/eloquent#defining-models
Laravel Validation Rules
or https://laravel.com/docs/5.8/validation#quick-writing-the-validation-logic
In your web.php, Add route names
Route::get('insert','ProductsController#insertform')->name('product.create');
Route::post('create','ProductsController#insert')->name('product.store');
In your view, change method to post and add action attribute and csrf field.
<form action="{{ route('product.store') }}" method="post">
#csrf
In Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class ProductsController extends Controller
{
public function insertform(){
return view('home');
}
public function insert(Request $request){
$productname = $request->input('title');
$description = $request->input('description');
$price = $request->input('price');
$data = array(
"title" => $productname,
"description" => $description,
"price" => $price
);
DB::table('products')->insert($data);
echo "Record inserted successfully.<br/>";
echo 'Click Here to go back.';
}
}
Alternate you can directly add action without route name
<form action="/create" method="post">
#csrf
In laravel 5.6 i can show you how to insert the data and display the data to the index page
so first of all i can code my route
in here we can use 2 routes
first is index page route
second is store and in store controller you can display your stored data.
Route::get('/FAQ_page', 'SettingController#FAQ_page')->name('FAQ_page');
Route::get('/FAQ_page/create', 'SettingController#FAQ_page_create')->name('FAQ_page.create');
Route::post('/FAQ_page/store', 'SettingController#FAQ_pagestore');
now make a database and connect to your module
this is your module
namespace App;
use Illuminate\Database\Eloquent\Model;
class FAQpage extends Model
{
protected $table = 'p66_FAQ_page';
public $timestamps = false;
protected $primaryKey = 'fid';
}
now make your controller like this
public function FAQ_page()
{
$data = FAQpage::get();
return view('SuperAdmin.settings.FAQ_page', compact('data'));
}
public function FAQ_page_create()
{
return view('SuperAdmin.settings.FAQ_page_create');
}
public function FAQ_pagestore(Request $request)
{
request()->validate([
'FAQ_question'=> 'required',
'FAQ_answer'=> 'required',
'Sort_order'=> 'required|max:4',
'FAQ_departments'=> 'required',
]);
$data = new FAQpage();
$data->FAQ_question = $request->get('FAQ_question');
$data->FAQ_answer = $request->get('FAQ_answer');
$data->Sort_order = $request->get('Sort_order');
$data->FAQ_departments = $request->get('FAQ_departments');
$data->Created_date = Carbon::now();
$data->save();
return redirect('/SuperAdmin/FAQ_page');
}
thank you

Pass id from controller index to store - Laravel

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]);

Laravel Eloquent delete by id

I'm trying to delete a single record by id. Instead, it deletes all records in that table.
Here's my code:
View
<form role="form" action="{{ route('status.delete', ['statusId' => $status->id]) }}" method="post">
<button type="submit" class="btn btn-default"><i class="fa fa-times"></i> Delete</button>
<input type="hidden" name="_token" value="{{ Session::token() }}">
</form>
Routes
Route::post('/status/{statusId}/delete', [
'uses' => '\Dashboard\Http\Controllers\StatusController#deleteStatus',
'as' => 'status.delete',
'middleware' => ['auth'],
]);
Controller
public function deleteStatus(Request $request, $statusId)
{
Auth::user()->statuses()->delete($statusId);
return redirect()->route('home')->with('success', 'Post deleted.');
}
Note: When I dd($statusId) it does provide the right ID for the status I'm deleting. So that part does work.
This is possible in Laravel 5.6 using the destroy method:
From the docs:
However, if you know the primary key of the model, you may delete the
model without retrieving it. To do so, call the destroy method
App\Model::destroy(1);
or to delete an array of ids:
App\Model::destroy([1, 2, 3]);
or by query:
App\Model::where('active', 0)->delete();
Unfortunately, the Eloquent builder does not support passing the id to delete.
Instead, you have to first find to model, then call delete on it:
$request->user()->statuses()->findOrFail($statusId)->delete();
you can delete the model by using another approach like
App\Models\ModelName::find(id)->delete()
but it throws nullPointerException that you have to handle
**Step 1 create route inside web.php**
Route::delete('/answers_delete/{id}', [App\Http\Controllers\AnswerController::class, 'delete'])->name('answers.delete');
**Step 2 Create method in your controller**
use App\Models\Answer; // use in top of this file
public function delete($id)
{
$ans = Answer::find($id);
$ans->delete();
session()->flash('success', 'Answer Deleted Successfully!!!');
return view('admin.anser.index');
}
**Step 3 define your route name inside form action(Note my case view file name index.blade.php and inside admin/answer/index.blade.php)*
<form action="{{ route('answers.delete', $answer->id) }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger" style="display: inline;">Delete</button>
</form>

Categories