Method App\Http\Controllers\SkillController::show does not exist. - Laravel 5.7 - php

I keep getting this error, when I try to create a skill on my project
Method App\Http\Controllers\SkillController::show does not exist.
I don't need a show() method because I don't need a show view of my skill object.
This is my route block look like
//Skill
Route::get('skill','SkillController#index');
Route::get('skill/create','SkillController#create');
Route::post('skill/store','SkillController#store');
Route::get('skill/{id}/edit', 'SkillController#edit');
Route::post('skill/{id}/update','SkillController#update');
Route::delete('skill/{id}/destroy','SkillController#destroy');
This is my entire SkillController
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Skill;
use Input, View, File, Image, SSH, Redirect,Response;
class SkillController extends Controller {
public function index(){
$skills = Skill::orderBy('updated_at', 'desc')->orderBy('created_at', 'asc')->where('img_path','==',NULL)->get();
$first_color = $skills[0]->color_code;
$second_color = $skills[1]->color_code;
$third_color = $skills[2]->color_code;
$fourth_color = $skills[3]->color_code;
$fift_color = $skills[4]->color_code;
return View::make('layouts.be.skills.index', get_defined_vars());
}
public function all(){
return Skill::all()->pluck('name');
}
public function create(){
$skillTypes = ['Build System','Development Environment','Server Management','Operating System','IDE','Creative Suite','Video Editing','Package Management','Git Repository','Web Scaffolding','CSS Precompiler','Scripting','Framework','DBMS','Unit Test','Automation Testing','Cloud Platform','Hosting Provider','Content Management', 'API', 'Authentication' , 'Integration','Language','Web Server','Project Managment','Documentation','Utility','Network Analyzer' ];
sort($skillTypes);
return View::make('layouts.be.skills.create', get_defined_vars());
}
public function edit($id){
$skillTypes = ['Build System','Development Environment','Server Management','Operating System','IDE','Creative Suite','Video Editing','Package Management','Git Repository','Web Scaffolding','CSS Precompiler','Scripting','Framework','DBMS','Unit Test','Automation Testing','Cloud Platform','Hosting Provider','Content Management', 'API', 'Authentication' , 'Integration','Language','Web Server','Project Managment','Documentation','Utility','Network Analyzer' ];
sort($skillTypes);
$skill = Skill::findOrFail($id);
return View::make('layouts.be.skills.edit', get_defined_vars());
}
public function store(){
$skill = new Skill;
$skill->type = Input::get('type');
$skill->name = Input::get('name');
$skill->value = Input::get('value');
$skill->color_code = Input::get('color_code');
$skill->save();
if (Input::hasFile('logo_path')) {
$image_path = '/assets/img/skill/';
$path = public_path() . $image_path;
$file = Input::file('logo_path');
$img_name = $skill->id.'.png';
$uploadSuccess = $file->move($path, $img_name);
$file_path = $path . $img_name;
$skill->img_path = $image_path . $img_name;
$crop_file = Image::make($file_path)->fit(20,20);
$crop_file->save($path . 'crop-'.$img_name, 65);
}else {
$skill->img_path = Input::get('logo_path');
}
$skill->save();
return Redirect::to('/skill') ->with('success','The skill was created succesfully!');
}
public function update($id){
$inputs = Input::all();
$skill = Skill::find($id);
$skill->name = Input::get('name');
$skill->type = Input::get('type');
$skill->value = Input::get('value');
$skill->color_code = Input::get('color_code');
$skill->save();
if (Input::hasFile('logo_path')) {
$image_path = '/assets/img/skill/';
$path = public_path() . $image_path;
$file = Input::file('logo_path');
$img_name = $skill->id.'.png';
$uploadSuccess = $file->move($path, $img_name);
$file_path = $path . $img_name;
$skill->img_path = $image_path . $img_name;
$crop_file = Image::make($file_path)->fit(20,20);
$crop_file->save($path . 'crop-'.$img_name, 65);
} else {
$skill->img_path = Input::get('logo_path');
}
$skill->save();
return Redirect::to('/skill') ->with('success','The skill was updated succesfully!');
}
public function destroy($id){
$skill = Skill::find($id);
$skill->delete();
$image_path = '/assets/img/skill/';
$path = public_path() . $image_path;
File::deleteDirectory($path);
return Redirect::to('/skill') ->with('success','The skill was deleted succesfully!');
}
public function skilldata(Request $request){
$skill = str_replace("-"," ",$request->skill);
$data = Skill::where(DB::raw('LOWER(type)'),'=',$skill)->get();
return response()->json($data, 200);
}
}
I also tried this 2 commands already
┌──[root#bheng]──[/home/forge/bheng]
└── php artisan cache:clear
Application cache cleared!
┌──[root#bheng]──[/home/forge/bheng]
└── composer dumpauto
Do not run Composer as root/super user! See https://getcomposer.org/root for details
Generating autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> #php artisan package:discover
Discovered Package: nesbot/carbon
Discovered Package: laravel/slack-notification-channel
Discovered Package: laravel/nexmo-notification-channel
Discovered Package: laravelcollective/remote
Discovered Package: htmlmin/htmlmin
Discovered Package: intervention/image
Discovered Package: laravelcollective/html
Package manifest generated successfully.
You have new mail in /var/mail/root
┌──[root#bheng]──[/home/forge/bheng]
└──
skill.create.blade.php
#extends('layouts.be.master')
#section('content')
<div class="card-body card-padding">
<div class="row">
{!! Form::open(array('class' => 'form-horizontal', 'role' =>'form', 'url'=>'skill/store','files' => true)) !!}
<div class="col-sm-4">
{{-- Name --}}
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" value="{{Request::old('name')}}" value="" name="name" class="form-control" id="name" placeholder="Name">
</div>
</div>
{{-- Type --}}
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Type</label>
<div class="col-sm-10">
<select name="type" class="form-control">
#foreach($skillTypes as $item)
<option value="{{ $item }}">{{ $item }}</option>
#endforeach
</select>
</div>
</div>
{{-- Value --}}
<div class="form-group">
<label class="col-sm-2 control-label">Value</label>
<div class="col-sm-8">
<br>
<input type="range" id="range-value" value="93" name="value">
</div>
<div class="col-sm-2">
<h3 id="text-value"></h3>
</div>
</div>
{{-- Color --}}
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Color</label>
<div class="col-sm-2">
<input type="color" name="color_code" class="form-control" placeholder="Color" id="example-color-input">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<a class="btn btn-default" href="/skill"> Cancel </a>
<button type="submit" class="btn btn-info">Create</button>
</div>
</div>
</div>
<div class="col-sm-8">
{{-- Icon --}}
<div class="form-group">
<label class="col-sm-2 control-label" >Icon</label>
<div class="col-sm-10">
<img name="logo_path" id="skill-icon" width="300px"><br><br>
<input type="file" class="form-control" name="logo_path" aria-describedby="fileHelp">
</div>
<label class="col-sm-2 control-label" >Icon URL </label>
<div class="col-sm-10">
<input id="url-logo" name="logo_path" type="text" class="form-control">
</div>
</div>
</div>
{!!Form::close()!!}
</div>
</div>
#stop
#section('custom-scripts')
<script type="text/javascript" src="/js/Vibrant.js"></script>
<script type="text/javascript">
function readLogo(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#skill-icon').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
// Update media preview with base64 image
$( "input[name*='logo_path']" ).change(function(){
readLogo(this);
});
$( "#url-logo" ).on('keyup',function(){
$('#skill-icon').attr('src', $( "#url-logo" ).val());
});
$('#text-value').text($('#range-value').val());
$('#range-value').change(function(){
$('#text-value').text($('#range-value').val());
});
// Icon
var icon = $('#skill-icon');
icon.attr('src', $( "#url-logo" ).val());
$( "#url-logo" ).on('keyup',function(){
var vibrant = new Vibrant(icon[0]);
var swatches = vibrant.swatches()
for (var swatch in swatches)
if (swatches.hasOwnProperty(swatch) && swatches[swatch])
// console.log(swatches[swatch].getHex());
var color = swatches[swatch].getHex();
$( "input[name*='color_code']" ).val(color)
console.log('%c >>>>>>>>>>>>>>', "color:" + String(color) + ";");
console.log('color',color);
// Vibrant #3c62ac
// Muted #7484ab
// DarkVibrant #345cab
// DarkMuted #101010
// LightVibrant #849ccc
});
</script>
#stop
Please let me know if you spot anything I should not do.

It just route ordering issue.
Make Route Order Like This :
//Skill
Route::post('skill/store','SkillController#store');
Route::get('skill','SkillController#index');
Route::get('skill/create','SkillController#create');
Route::post('skill/{id}/update','SkillController#update');
Route::delete('skill/{id}/destroy','SkillController#destroy');
Route::get('skill/{id}/edit', 'SkillController#edit');
OR
If your making CRUD module then use Laravel 'Resource Controllers' routing method https://laravel.com/docs/5.7/controllers#resource-controllers
First Create Resource Controller : Run Below command In terminal
php artisan make:controller SkillController --resource
Then Put Below Line In 'routes/web.php' file
Route::resource('skill', 'SkillController');

You don't have a method= on your
And that is why assume Route::resource set up it will assume you're trying to access the show method.
Form::open(array('url' => 'foo/bar', 'method' => 'POST'))

Yeah as I thought in my initial comment, you haven't specified an action for the form - this should resolve your issues:
{!! Form::open(array('class' => 'form-horizontal', 'role' =>'form', 'url'=>'skill/store', 'action' => 'SkillController#store' ,'files' => true)) !!}
also, your routes are incorrect - your routes should be:
Route::get('skill','SkillController#index');
Route::get('skill/create','SkillController#create');
Route::post('skill/store','SkillController#store');
Route::get('skill/{id}/edit', 'SkillController#edit');
Route::patch('skill/{id}/update','SkillController#update'); //this should be put or patch not post
Route::delete('skill/{id}/destroy','SkillController#destroy');

if you already manually wrote routes like this
//Skill
Route::get('skill','SkillController#index');
Route::get('skill/create','SkillController#create');
Route::post('skill/store','SkillController#store');
Route::get('skill/{id}/edit', 'SkillController#edit');
Route::post('skill/{id}/update','SkillController#update');
Route::delete('skill/{id}/destroy','SkillController#destroy');
then you dont need this one, this code should be somewhere on your routes
Route::resource('skills','SkillController');
or
you can remove your entire manual written routes of skillcontroller
change it into this one
Route::resource('skills', 'SkillController', ['only'=> ['index','create','store','delete','edit','update']]);

Related

Is there a way to handle this error when updating a record in Laravel?

So this is my web.php
<?php
use App\Http\Controllers\BookingController;
use App\Http\Controllers\BookingRoomController;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\CustomerController;
use App\Http\Controllers\GuestController;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\RoomController;
use App\Models\Customer;
use App\Models\Room;
use App\Models\Guest;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome',[
'customerCount' => Customer::count(),
'guestCount' => Guest::count(),
'roomCount' => Room::count()
]);
});
// Customer Controller
Route::get('/customers',[CustomerController::class,'index'])->name('customers.index');
Route::get('/customers/add',[CustomerController::class,'create'])->name('customers.create');
Route::post('/customers',[CustomerController::class,'store'])->name('customers.store');
Route::post('/customers/update',[CustomerController::class,'update'])->name('customers.update');
Route::get('/customers/search',[CustomerController::class,'search'])->name('customers.search');
Route::get('/customers/{id}',[CustomerController::class,'show'])->name('customers.show');
Route::delete('/customers/{id}',[CustomerController::class,'destroy'])->name('customers.destroy');
// Guest Controller
Route::get('/guests',[GuestController::class,'index'])->name('guests.index');
Route::get('/guests/add',[GuestController::class,'create'])->name('guests.create');
Route::post('/guests',[GuestController::class,'store'])->name('guests.store');
Route::post('/guests/update',[GuestController::class,'update'])->name('guests.update');
Route::get('/guests/search',[GuestController::class,'search'])->name('guests.search');
Route::get('/guests/{id}',[GuestController::class,'show'])->name('guests.show');
Route::delete('/guests/{id}',[GuestController::class,'destroy'])->name('guests.destroy');
// Rooms
Route::get('/rooms',[RoomController::class,'index'])->name('rooms.index');
Route::post('/rooms/update',[RoomController::class,'update'])->name('rooms.update');
Route::get('/rooms/{id}',[RoomController::class,'show'])->name('rooms.show');
// Bookings
Route::get('/bookings',[BookingController::class,'index'])->name('bookings.index');
Route::get('/bookings/create',[BookingController::class,'create'])->name('bookings.create');
Route::post('/bookings',[BookingController::class,'store'])->name('bookings.store');
Route::get('/bookings/{id}',[BookingController::class,'show'])->name('bookings.show');
// Booking Rooms
Route::post('/bookingrooms',[BookingRoomController::class,'store'])->name('bookingrooms.store');
// Authentication
Auth::routes();
Route::get('/home', [HomeController::class, 'index'])->name('home');
// Route::get('/email/verify', function () {
// return view('auth.verify-email');
// })->middleware('auth')->name('verification.notice');
// Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) {
// $request->fulfill();
// return redirect('/home');
// })->middleware(['auth', 'signed'])->name('verification.verify');
This is my customer controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Customer;
class CustomerController extends Controller
{
public function __construct()
{
$this->middleware('auth')->except(['store','create']);
}
public function index(){
$customer = Customer::latest()->get();
return view('customers.index',['customer' => $customer]);
}
public function show($id){
$customer = Customer::findOrFail($id);
return view('customers.show',['customer' => $customer]);
}
public function create(){
return view('customers.create');
}
public function store(){
$customer = new Customer();
$customer->title = request('title');
$customer->first_name = request('firstname');
$customer->last_name = request('lastname');
$customer->date_of_birth = request('dateofbirth');
$customer->street = request('street');
$customer->town = request('town');
$customer->province = request('province');
$customer->postal_code = request('postalcode');
$customer->home_phone = request('homephone');
$customer->work_phone = request('workphone');
$customer->mobile_phone = request('mobilephone');
$customer->email = request('email');
$customer->save();
return redirect('/')->with('mssg','Added customer successfully!');
}
public function update(Request $req){
$customer = Customer::findorFail($req->id);
$customer->title = $req->title;
$customer->first_name = $req->firstname;
$customer->last_name = $req->lastname;
$customer->date_of_birth = $req->dateofbirth;
$customer->street = $req->street;
$customer->town = $req->town;
$customer->province = $req->province;
$customer->postal_code = $req->postalcode;
$customer->home_phone = $req->homephone;
$customer->work_phone = $req->workphone;
$customer->mobile_phone = $req->mobilephone;
$customer->email = $req->email;
$customer->save();
return redirect('/')->with('mssg','Updated customer successfully!');
}
public function search(Request $req){
$search = $req->get('search-customer');
$customer = Customer::where('first_name','like','%'.$search.'%')->paginate(5);
return view('customers.index',['customer' => $customer]);
// $records = ['first_name' => '%'.$search.'%',
// 'title' => '%'.$search.'%',
// 'last_name' => '%'.$search.'%'
// ];
}
public function destroy($id){
$customer = Customer::findOrFail($id);
$customer->delete();
return redirect('/')->with('mssg','Customer has been deleted!');
}
public function quantity(){
$customer = Customer::all();
return view('/',['customers' => $customer]);
}
}
This is my show.blade.php
#extends('layouts.app')
#section('content')
<div class="insert-customer-container-main">
<h1>Customer Information</h1>
<p>Please fill in the following</p>
<form class="insert-customer-container" action="{{ route('customers.update') }}" method="POST">
#csrf
{{-- get in controller to manipulate updating --}}
<input type="hidden" name="id" value="{{$customer->id}}">
<div class="customer-input-container row-one">
<div class="customer-input">
<label for="title">Title</label><br/>
<input style="width:945px" type="text" name="title" value="{{$customer->title}}" required>
</div>
</div>
<div class="customer-input-container row-two">
<div class="customer-input">
<label for="firstname">First Name</label><br/>
<input type="text" name="firstname" value="{{$customer->first_name}}">
</div>
<div class="customer-input">
<label for="lastname">Last Name</label><br/>
<input type="text" name="lastname" value="{{$customer->last_name}}">
</div>
<div class="customer-input">
<label for="dateofbirth">Date of Birth</label><br/>
<input type="date" name="dateofbirth" value="{{$customer->date_of_birth}}">
</div>
</div>
<div class="customer-input-container row-three">
<div class="customer-input">
<label for="street">Street</label><br/>
<input type="text" name="street" value="{{$customer->street}}">
</div>
<div class="customer-input">
<label for="town">Town</label><br/>
<input type="text" name="town" value="{{$customer->town}}">
</div>
<div class="customer-input">
<label for="province">Province</label><br/>
<input type="text" name="province" value="{{$customer->province}}">
</div>
</div>
<div class="customer-input-container row-four">
<div class="customer-input">
<label for="homephone">Home Phone</label><br/>
<input type="number" name="homephone" value="{{$customer->home_phone}}">
</div>
<div class="customer-input">
<label for="workphone">Work Phone</label><br/>
<input type="number" name="workphone" value="{{$customer->work_phone}}">
</div>
<div class="customer-input">
<label for="mobilephone">Mobile Phone</label><br/>
<input type="number" name="mobilephone" value="{{$customer->mobile_phone}}">
</div>
</div>
<div class="customer-input-container row-five">
<div class="customer-input">
<label for="postalcode">Postal Code</label><br/>
<input type="number" name="postalcode" value="{{$customer->postal_code}}">
</div>
<div class="customer-input">
<label for="email">Email Address</label><br/>
<input style="width:50vw;" type="email" name="email" value="{{$customer->email}}">
</div>
</div>
<input class="submit" type="submit" value="Update">
</form>
<form class="delete-form" action={{ route('customers.destroy', $customer->customer_id) }} method="POST">
#csrf
#method('DELETE')
<input type="submit" class="submit delete-btn" value="Delete">
</form>
</div>
#endsection
So my question is
When I'm editing a specific record and when I submit it, it redirects me to 404 page which is not what I'm expecting. Is there a way to fix this problem? I'm new in laravel and hoping someone could help. Thanks everyone!
May be your Route wrong
Route::get('/customers',[CustomerController::class,'index'])->name('customers.index');
Route::get('/customers/add',[CustomerController::class,'create'])->name('customers.create');
Route::post('/customers',[CustomerController::class,'store'])->name('customers.store');
Route::post('/customers/update',[CustomerController::class,'update'])->name('customers.update');
Route::get('/customers/search',[CustomerController::class,'search'])->name('customers.search');
Route::get('/customers/{id}',[CustomerController::class,'show'])->name('customers.show');
Route::delete('/customers/{id}',[CustomerController::class,'destroy'])->name('customers.destroy');
after
Route::resource('customers', 'CustomerController');
edit your all routes by resource after that try and also check your
route list
php artisan route:list
404: Not found
I think that is due to the wrong url you have passed as an action.
try to clean up your routes:
Route::group(['prefix' => 'customers', 'as' => 'customers.'], function() { Route::post('/update',[CustomerController::class,'update'])->name('customers.update'); });

I'm stuck for 2 days with probably an obvious thing - PHP + Laravel image update

I started creating an e-commerce platform and I'm stuck with a problem I can't solve for 2 days.. It's probably something obvious but I just can't find the solution for this. Could you help me with this, please? I get this error:
Missing required parameters for [Route: images.update] [URI: dashboard/images/{image}]. (View: C:\xampp\htdocs\ecommerce\ecommerce\resources\views\website\admin\product_image\update.blade.php)
update.blade.php
#extends('website.admin.layouts.main')
#section('content')
<div class="col-md-12 col-sm-12 ">
<div class="x_panel">
<div class="x_title">
<h2>Zaktualizuj obraz</h2>
<div class="clearfix"></div>
</div>
<div class="x_content">
<br />
<form id="updateimage-form" data-parsley-validate="" class="form-horizontal form-label-left" novalidate="" enctype="multipart/form-data" method="POST" action="{{route('images.update', $productImage->id)}}">
#csrf
#method('PUT')
<div class="item form-group">
<label class="col-form-label col-md-3 col-sm-3 label-align" for="first-name">Produkt<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 ">
<select class="form-control" name="product_id">
#foreach ($product as $prodcat)
<option value="{{$prodcat -> id}}" name="product_id">{{ $prodcat -> product_name }}</option>
#endforeach
</div>
</div>
<div class="ln_solid"></div>
<div class="item form-group">
<label class="col-form-label col-md-3 col-sm-3 label-align" for="first-name">Nazwa obrazu<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 ">
<input type="text" id="img_title" name="img_title" placeholder="Image Title" value="{{ $productImage -> image_name }}" required="required" class="form-control ">
</div>
</div>
<div class="item form-group">
<label class="col-form-label col-md-3 col-sm-3 label-align" for="first-name">Wgraj obraz<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 ">
<input type="file" name="img" id="img" onchange="fileSelected();"/>
</div>
</div>
<div class="item form-group">
<div class="col-md-6 col-sm-6 offset-md-3">
<button class="btn btn-primary" type="reset">Wyczyść</button>
<button type="submit" class="btn btn-success">Zaktualizuj obraz</button>
</div>
</div>
</form>
</div>
</div>
</div>
#endsection
models\ProductImage.php
<?php
namespace App\Models\models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ProductImage extends Model
{
protected $fillable = [
'product_id',
'image_name',
'image',
'slug',
'status'
];
public function product()
{
return $this -> belongsTo('App\Models\models\Product');
}
}
ProductImageController.php
<?php
namespace App\Http\Controllers;
use App\Models\models\Product;
use App\Models\models\ProductImage;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class ProductImageController extends Controller
{
public function index()
{
$productImage = ProductImage::all();
return view('website.admin.product_image.index', compact('productImage'));
}
public function create()
{
$product = Product::all();
return view('website.admin.product_image.create', compact('product'));
}
public function store(Request $request)
{
$slug = Str::slug($request->image_name, '-');
$image = time().'.'.$request->image->extension();
$request->image->move(public_path('images'), $image);
ProductImage::create([
'image_name'=>$request->image_name,
'image'=>$image,
'product_id'=>$request->product_id,
'slug'=>$slug,
]);
return redirect()->route('images.index');
}
public function show(ProductImage $ProductImage)
{
//
}
public function edit(ProductImage $productImage)
{
$product = Product::all();
return view('website.admin.product_image.update',compact('productImage','product'));
}
public function update(Request $request, ProductImage $productImage)
{
$slug=Str::slug($request->image_name,'-');
if($request->image)
{
$image = time() .'.'. $request -> image -> extension();
$request->image->move(public_path('images'), $image);
}
else
{
$image=$productImage->image;
}
$productImage->update([
'image_name'=>$request->image_name,
'image'=>$image,
'product_id'=>$request->product_id,
'slug'=>$slug,
]);
return redirect()->route('images.index');
}
public function destroy(productImage $productImage)
{
$productImage->delete();
return redirect()->route('images.index');
}
}
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('website.shop.layouts.main');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('/dashboard', [App\Http\Controllers\DashboardController::class, 'index'])->name('dashboard.index');
Route::resource('/dashboard/categories', 'App\Http\Controllers\ProductCategoryController');
Route::resource('/dashboard/product', 'App\Http\Controllers\ProductController');
Route::resource('/dashboard/images', 'App\Http\Controllers\ProductImageController');
update.blade.php
<form method="post" action="{{route('images.update', $productImage->id)}}" enctype="multipart/form-data">
#csrf
#method('PUT')
<div class="form-group">
<label for="filename">Select your Image</label>
<input type="file" name="image" class="form-control">
<button type="submit" class="btn btn-primary btn-lg">Update</button>
</div>
</form>
ProductImageController.php
<?php
namespace App\Http\Controllers;
use App\Models\models\ProductImage;;
use Illuminate\Http\Request;
class DocumentController extends Controller
{
public function update(Request $request, $productId){
$product = ProductImage::findOrFail($productId);
if($request->hasfile('image'))
{
$file = $request->file('image');
$name=$file->getClientOriginalName();
$file->move(public_path().'/uploads/ProductImages/', $name);
$file = $name;
$product->image = $file;
}
$product->save();
return redirect()->back();
}
}
I solved this, the problem was with "images" name in route. I changed it to something else everywhere and it works now.
action="{{route('images.update', $productImage->id)}}" is incorrect way of calling route() helper function. Consider the following snippet;
action="{{route('images.update', [
'image' => $productImage->id
])}}"
For more details about route() helper, see this link; https://laravel.com/docs/8.x/helpers#method-route
You don't have Model Binding happening here you have Dependency Injection happening instead. For Implicit Route Model Binding to take place you have to match the type hinted parameter of your method to the name of the route parameter. In your case the route parameter is named image, not productImage. So you are getting an empty new instance of ProductImage instead of the replacement for the Route Model Binding.
Change your controller's parameter to match the route parameter:
vvvvv
public function edit(ProductImage $image)
You would need to change this in all the methods you want the Implicit Binding for, unless you want to override the parameter used in the route.
vvvvv
public function update(Request $request, ProductImage $image)
At the moment you are passing an empty model to your view which is then trying to use it's "id" to generate a route, but "id" is null and route parameters can no to null.

Laravel Error: The POST method is not supported for this route. Supported methods: GET, HEAD

Good evening , for school i am trying to create a simple CRUD app, using laravel 6 and mongoDB.
I can get read, update and delete working but creat fails with The POST method is not supported for this route. Supported methods: GET, HEAD.. I have searched the answers here and other sites but im stuck for 2 days now (could be something very silly but im not seeing it)
my routes are:
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/post/{_id?}', 'PostController#form')->name('post.form');
Route::post('/post/save/', 'PostController#save')->name('post.save');
Route::put('/post/update/{_id}', 'PostController#update')->name('post.update');
Route::get('/post/delete/{_id}', 'PostController#delete')->name('post.delete');
form.blade 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">Post Form</div>
<div class="card-body">
#if($data)
<form action = "{{Route ('post.update', $data->_id)}}" method="post">
#csrf
#method('PUT')
<div class="form-group">
<label for="usr">Title:</label>
<input type="text" class="form-control" name="title" value = "{{$data->title}}" >
</div>
<div class="form-group">
<label for="comment">Content:</label>
<textarea class="form-control" rows="5" name="content">{{$data->content}}</textarea>
</div>
<p align="center"> <button class="btn btn-primary">save</button></p>
</form>
#else
<form action = "{{Route ('post.form')}}" method="post">
#csrf
<div class="form-group">
<label for="usr">Title:</label>
<input type="text" class="form-control" name="title">
</div>
<div class="form-group">
<label for="comment">Content:</label>
<textarea class="form-control" rows="5" name="content"></textarea>
</div>
<p align="center"> <button class="btn btn-primary">save</button></p>
</form>
#endif
</div>
</div>
</div>
</div>
#endsection
and my PostController is:
<?php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
//
public function form($_id = false){
if($_id){
$data = Post::findOrFail($_id);
}
$data = false;
return view ('post.form', compact('data'));
}
public function save (Request $request){
$data = new Post($request->all());
$data->save();
if($data){
return redirect()->route('home');
}else{
return back();
}
}
public function update (Request $request, $_id){
$data = post::findOrFail($_id);
$data->title = $request->title;
$data->content = $request->content;
$data->save();
/* return response()->json([
'name' => 'Abigail',
'state' => 'CA'
]); */
if($data){
return redirect()->route('home');
}else{
return back();
}
}
public function delete($_id){
$data = post::destroy($_id);
if($data) {
return redirect()->route('home');
}
else {
dd('error cannot delete this post');
}
}
}
Anybody any idea what i am missing?
Thanks in advance
You have to replace this line <form action = "{{Route ('post.form')}}" method="post"> with <form action = "{{Route ('post.save')}}" method="post">
You are using wrong route. Please change to Route ('post.save')
EDIT: I found that one myself, the PostControler didnt return a view if there was an $_id
Thanks for the help everyone!
Thanks for pointing that out, it did bring my from back to life :) However it breaks the update function :S.
When i now click on the edit button, the form does no longer get filled with the data for the post, and "save" creates a new post in stead of updating it.

Laravel: Can't get uploaded images to display

On my website, a registered user can create a post by uploading an image and writing a description. I have made it where a unique image name is created based on the user's image name and the time they upload the image. Once a name is created it is stored in the post database. The image name successfully gets stored and so does the actual image. However, when it comes to actually displaying the image on the post nothing comes up like it can't find the image. I can't seem to figure out why this is.
Here is my PostController.php class:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
class PostController extends Controller
{
public function getDashboard(){
$posts = Post::orderBy('created_at', 'desc')->get();
return view('dashboard', ['posts' => $posts]);
}
public function postCreatePost(Request $request){
$this->validate($request, [
'body' => 'required',
'cover_image' => 'image|nullable|max:1999'
]);
if($request->hasFile('cover_image')){
$filenameWithExt = $request->file('cover_image')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('cover_image')->getClientOriginalExtension();
$fileNameToStore = $filename . '_' . time() . '.' . $extension;
$path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);
} else{
$fileNameToStore = 'noimage.jpg';
}
$post = new Post();
$post->body = $request['body'];
$post->cover_image = $fileNameToStore;
$message = 'There was an error';
if($request->user()->posts($post)->save($post)){; //points here
$message = 'post successfully created';
}
return redirect()->route('dashboard')->with(['message' => $message]);
}
public function getDeletePost($post_id){
$post = Post::where('id', $post_id)->firstOrFail();
$post->delete();
return redirect()->route('dashboard')->with(['message' => 'post deleted']);
}
}
Here is my view:
<section class="row new-post">
<div class="col-md-6 col-md-offset-3">
<form action="{{ route('postcreate') }}" method="post" enctype="multipart/form-data">
<div class="form-group">
<input type="file" name="cover_image" class="form-control" id="cover_image">
</div>
<div class="form-group">
<textarea class="form-control" name="body" rows="5" placeholder="your post"></textarea>
</div>
<button type="submit" class="btn btn-primary">Create post</button>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
</div>
</section>
#foreach($posts as $post)
<section class="row posts">
<div class="col-md-6">
<article class="post">
<p>{{ $post->body }}</p>
<div class="info">Posted by {{ $post->user->first_name }} {{ $post->user->last_name }} on {{ $post->created_at }}</div>
<div class="interaction">
Like|
#if(Auth::user() == $post->user)
Edit|
Delete
#endif
</div>
</article>
</div>
<div class="col-md-6">
<img src="/storage/cover_images/{{ $post->cover_image }}">
</div>
</section>
#endforeach
Here is my migration:
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('cover_image');
$table->text('body');
$table->integer('user_id');
});
You're storing as public/cover_images but echoing out storage/cover_images.
Updated following your response;
Why not try using
<img src="{{ asset('storage/cover_images/' . $post->cover_image) }}">

decode and move base64 encoded image in laravel

I am trying to implement a image upload with other form elements with dropzone.js in laravel. So far I've managed to display the drag and drop image upload view with other form elements. And also get POST details from the submitted form. But when dropzone is passing the uploaded image to the database data save function it encode image with base64. I think I've managed to get the file extension also. And when I submit the button it gives me this error "Call to a member function move() on string" . Please put me in the right direction.
Here is the Form
<form class="form-horizontal" action="{{ route('save-slider-content') }}" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="box-body">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="sliderTitle" id="sliderTitle" placeholder="Title of the post goes here">
</div>
</div>
<input type="hidden" name="date" id="date" value="<?php echo date("d-m-Y"); ?>">
<div class="form-group">
<label for="image" class="col-sm-2 control-label">Image</label>
<input hidden id="file" name="file"/>
<div class="col-sm-10">
<div class="dropzone needsclick dz-clickable" id="fileUpload">
<div class="dz-default dz-message">
<i class="fa fa-image fa-5x"></i>
<h3 class="sbold">Drop an image here to upload</h3>
<span>You can also click to open file browser</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Link</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="sliderLink" id="sliderLink" placeholder="Provide a link">
</div>
</div>
</div><br>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-default">Cancel</button>
<button type="submit" class="btn btn-info pull-right">Post</button>
</div>
<!-- /.box-footer -->
</form>
Here is the dropzone configuration
<script type="text/javascript">
Dropzone.options.fileUpload = {
url: "save-slider-content",
addRemoveLinks: true,
accept: function(file) {
let fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onloadend = function() {
let content = fileReader.result;
$('#file').val(content);
file.previewElement.classList.add("dz-success");
}
file.previewElement.classList.add("dz-complete");
}
}
</script>
Route
Route::post('store-slider-content', [ 'as' => 'save-slider-content', 'uses' => 'SliderContent#save_slider_data']);
save_slider_data function in Controller
public function save_slider_data(Request $request)
{
$slider = new Slider;
$slider->title = $request->sliderTitle;
$slider->title_sin = $request->sliderTitleSin;
$slider->date = $request->date;
$slider->link = $request->sliderLink;
$file = $request->file;;
$image_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $file));
$f = finfo_open();
$mime_type = finfo_buffer($f, $image_data, FILEINFO_MIME_TYPE);
$imageName = time().'.'.$mime_type;
$image_data->move(public_path('slider_uploads'), $imageName);
return response()->json(['success'=>$imageName]);
$slider->img_url = $imageName;
$slider->save();
}
Edited to include the logic for either Symfony\Component\HttpFoundation\File\File or Illuminate\Support\Facades\File (Illuminate\Filesystem\Filesystem)
move is a method of a File object, but $image_data is just a string. So one thing you could do is write the decoded image to a temp file, instantiate a File of it, and move it, like
//... your code ...
$image_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $file));
// ... and then:
//grab a new tmp file
$tmpFilePath=sys_get_temp_dir().'/'.uniqid();
//write the image to it
file_put_contents($tmpFilePath, $image_data);
//move it.
//give it a name
$imageName = time().'.'.str_replace("image/","",$mime_type);
//if using Symfony\Component\HttpFoundation\File\File;
//get an instance of File from the temp file and call ->move on it
$tmpFile=new File($tmpFilePath);
$tmpFile->move(public_path('slider_uploads'), $imageName);
//or if using File facade
File::move($tmpFilePath, public_path("slider_uploads/$imageName"));
//...and then, back to your code...
$slider->img_url = $imageName;
$slider->save();
return response()->json(['success'=>$imageName]);
}
You can do this:
In config/filesystems.php, register a new disk slider_uploads
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'slider_uploads' => [
'driver' => 'local',
'root' => public_path('slider_uploads')
]
]
And then use your new disk in storing your image
$image_data = $request->file;
#list($type, $image_data ) = explode(';', $image_data );
#list(, $image_data ) = explode(',', $image_data );
if($image_data !=""){ // storing image in public/slider_uploads/ Folder
\Storage::disk('slider_uploads')->put($imageName, base64_decode($image_data ));
}

Categories