Can't update in database data. Laravel - php

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

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

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

Perform specific action on button in Bootstrap modal (Laravel)

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

Laravel redirect() to is not generating the correct url

I would like to start by apologizing for the newbish question.
I'm in the process of making a simple CRUD controller on Laravel.
My create method is as follows:
public function create(Request $request)
{
$dummy = new Dummy();
$dummy->title = $request->title;
$dummy->content = $request->dummy_content;
$dummy->created_at = new \DateTime();
$dummy->updated_at = new \DateTime();
$dummy->save();
return redirect()
->route('index/view/', ['id' => $dummy->id])
->with('message', 'Dummy created successfully');
}
my view method:
public function view($id)
{
$dummy = Dummy::find($id);
return view('index/view', [
'dummy' => $dummy
]);
}
my corresponding routes:
Route::get('index/view/{id}', 'IndexController#view');
Route::post('index/create', 'IndexController#create');
and my form:
<form action="create" method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" class="form-control">
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea name="dummy_content" cols="80" rows="5" class="form-control"></textarea>
</div>
<button type="submit" class="btn btn-default btn-sm">Submit</button>
</form>
When I submit my form I get the following exception:
InvalidArgumentException in UrlGenerator.php line 314:
Route [index/view/] not defined.
I've been stuck here for quite some time and I still can't figure out why I'm not generating my route properly.
What am I missing?
You are trying to call a route when instead you should call the controller. This will do the trick
return redirect()->action('IndexController#view', ['id' => $id])->with($stuff);
Also, i suggest you to define aliases to routes, so you could do something like
In your controller:
return Redirect::route('route_alias', ['id' => $id])->with($stuff);
In your routes:
Route::get('/index/view/{id}', [
'as' => 'route_alias',
'uses' => 'IndexController#view'
]);

how to print the database content on a desired page?

I am using laravel 5.2. I want to print the database content that is stored in my database dynamically on the desired page. I tried but an error appears everytime i.e;( undefined variable:). I just want to print whatever content I store in my database table dynamically.
My code is here:
My model name is:gallery
My routes:
Route::get('/gallery/list' ,[
'uses'=>'gallerycontroller#viewgallerylist',
'as'=>'viewgallery'
]);
Route::post('/gallery/save' ,[
'uses'=>'gallerycontroller#savegallery',
'as'=>'savegallery'
]);
My controller:
public function viewgallerylist()
{
$galleries = gallery::all();
return view('gallery')->with('galleries', $galleries);
}
public function savegallery(Request $request)
{
$gallery1=$request['gallery_name'];
$gallery=new gallery();
$gallery->name=$gallery1;
$gallery->save();
return redirect()->route('viewgallery');
}
My desired page:
<form method="post" action="{{ route('savegallery') }}">
<input class="form-control" type="text" name="gallery_name">
<button type="submit" class="btn btn-primary" id="upl">Create+</button>
<input type="hidden" value="{{ Session::token() }}" name="_token">
</form>
#foreach($galleries as $gallery)
<p>{{ $gallery->name }}</p>
#endforeach
Most model Classes will have a capital letter. Are you sure your Model isn't called Gallery instead of gallery?
which means that you need to call Gallery::all() in your controller and make sure use App\Gallery; is at the top of your page.
public function viewgallerylist()
{
$galleries = Gallery::all();
return view('gallery')->with('galleries', $galleries);
}
The problem might be with your model.... please provide a larger view
Route::get('/' ,[
'uses'=>'gallerycontroller#viewgallerylist',
'as'=>'viewgallery'
]);
Route::post('/' ,[
'uses'=>'gallerycontroller#savegallery',
'as'=>'savegallery'
]);

Categories