Laravel 9 dropzone "app\models\examplemodel not found" error - php

I'm asking you because I can't solve my problem.
file upload no problem but db insert is error
my blade code
<form action="{{ route('admin_multiupload_store') }}" method="POST" enctype="multipart/form-data" class="dropzone" id="image-upload">
#csrf
<input type="hidden" name="type" value="{{ $type }}">
<input type="hidden" name="id" value="{{ $id }}">
</form>
my javascript code
<script type="text/javascript">
new Dropzone("#image-upload", {
maxFilesize:12,
acceptedFiles:".jpeg,.jpg,.png,.gif,.svg",
addRemoveLink:true,
timeout: 5000,
success: function(file, response){
Swal.fire({
icon: 'success',
title: 'İşlem Başarılı...',
text: '{!! session()->get('success') !!}'
});
},
error: function(file, response){
return false;
}
})
</script>
my controller code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use app\Models\MultiImageModel;
class MultiImageController extends Controller
{
public function index($type, $id) {
return view('admin.multiupload', compact('type','id'));
}
public function store(Request $request) {
$image = $request->file('file');
$imageName = time().rand(1,1000).'.'.$image->extension();
$image->move(public_path('uploads/'),$imageName);
$image_data = new MultiImageModel();
var_dump($image_data);
$image_data->upload_type = $request->type;
$image_data->upload_id = $request->id;
$image_data->upload_filephp = $imageName;
$image_data->save();
return response()->json(['success'=> $imageName]);
}
}
model code
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class MultiImageModel extends Model
{
protected $table = 'multi_image_models';
use HasFactory;
}
the error i encountered
enter image description here
Waiting for your replies, thanks :)
uploading the file to the directory and saving it to the database, but I can't save it to the database. only file upload is successful

In the statement where you import the model class, capital letter "App" in the controller

Related

Laravel and FilePond sending chunks

Hi has anyone tried to use FilePond with Laravel to upload files in chunks ?
I am trying to do that but I dont know how to get the content of a PATCH method.
The upload starts, and a receive a bunch of PATCH methods, I see (Network Tab in Dev Mode Firefox) that they are different, because the offset changes.
Let me know if you need more details to help me.
My blade view (where the js is located):
<form action="{{ route('upload.store') }}" enctype="multipart/form-data"
method="post">
#csrf
<input class="" id="imageUploadFilePond" name="file" type="file">
<button class="btn btn-primary" type="submit">Submit</button>
</form>
#push('scripts')
<script src="https://unpkg.com/filepond#^4/dist/filepond.js"></script>
<script>
const inputElement = document.querySelector('#imageUploadFilePond');
const pond = FilePond.create(inputElement, {
server: {
url: '/upload',
patch: "/",
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
},
chunkUploads: true,
chunkSize: 1048576,
chunkForce: true,
});
</script>
#endpush
In my UploadController.php my methods :
public function store(Request $request)
{
if ($request->file === '{}') {
return uniqid();
}
return '';
}
public function update(Request $request, $id)
{
$uploadOffset = $request->header('upload-offset');
$uploadLenght = $request->header('upload-length');
$uploadName = $request->header('upload-name');
$numberOfChunks = $uploadLenght / self::CHUNKSIZE;
$currentChunk = $uploadOffset / self::CHUNKSIZE;
return $id;
}

Argument 1 passed to Symfony\Component\HttpFoundation\Response::setContent() with Axios Vue and Laravel 7

I am using Laravel 7 with Vue and Axios and I have run across this error but cannot seem to find out why I am getting it. I am using api routes in my Laravel app for contacts, No Controller and One Contacts Model. I have one vue component named Contacts.vue. When trying to fetch the data for the first time, I am met with a 500 internal server error and when I try to visit the route in question, api/contacts, I am met with the following error:
Argument 1 passed to Symfony\Component\HttpFoundation\Response::setContent() must be of the type string or null, object given, called in C:\laragon\www\contactstore\vendor\laravel\framework\src\Illuminate\Http\Response.php on line 65
To me, as a person new to Laravel, I am not sure how to trace down the problem. Unless there have been changes to axios compared to the way I am trying to use it, I haven't the slightest clue. So, Any help would be greatly appreciated. Thank you.
Here is the Contact.vue
<template>
<div>
<h1>Contacts</h1>
<form
action="#"
#submit.prevent="edit ? updateContact(contact.id) : createContact()"
>
<div class="form-group">
<label for="">Name</label>
<input
v-model="contact.name"
type="text"
name="name"
class="form-control"
placeholder="Enter Contact Name"
/>
</div>
<div class="form-group">
<label for="">Email</label>
<input
v-model="contact.email"
type="email"
name="email"
class="form-control"
placeholder="Enter Contact Email"
/>
</div>
<div class="form-group">
<label for="">Phone</label>
<input
v-model="contact.name"
type="text"
name="phone"
class="form-control"
placeholder="Enter Contact Phone Number"
/>
</div>
<div class="form-group">
<button v-show="!edit" type="submit" class="btn btn-primary">
New Contact
</button>
<button v-show="edit" type="submit" class="btn btn-secondary">
Update Contact
</button>
</div>
</form>
</div>
</template>
<script>
export default {
data: function () {
return {
edit: false,
list: [],
contact: {
id: "",
name: "",
email: "",
phone: "",
},
};
},
mounted: function () {
console.log("Contacts Component Loaded...");
this.fetchContactList();
},
methods: {
fetchContactList: function () {
console.log("Fetching contacts...");
axios
.get("api/contacts")
.then((response) => {
console.log(response.data);
this.list = response.data;
})
.catch((error) => {
console.log(error);
});
},
createContact: function () {
console.log("Creating Contact... ");
let self = this;
let params = Object.assign({}, self.contact);
axios
.post("api/contact/store", params)
.then(function () {
self.contact.name = "";
self.contact.email = "";
self.contact.phone = "";
self.edit = false;
self.fetchContactList();
})
.catch(function (error) {
console.log(error);
});
},
updateContact: function (id) {
console.log("Updating Contact... " + id);
},
},
};
</script>
My Contact model in the Models folder under App
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
//
}
My api.php for the routes
<?php
use App\Models\Contact;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::get('contacts', function () {
return Contact::latest()->orderBy('created_at', 'desc');
});
Route::get('contact/{id}', function ($id) {
return Contact::findOrFail($id);
});
Route::post('contact/store', function (Request $request) {
return Contact::create([
'name' => $request->input('name'),
'email' => $request->input('email'),
'phone' => $request->input('phone'),
]);
});
Route::patch('contact/{id}', function (Request $request, $id) {
Contact::findOrFail($id)->update([
'name' => $request->input('name'),
'email' => $request->input('email'),
'phone' => $request->input('phone'),
]);
});
Route::delete('contact/{id}', function ($id) {
return Contact::destroy($id);
});
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
and I am calling it all from within the default welcome.blade.php with
<contacts></contacts>
Again, if you can help me, I would certainly appreciate it. Thank you in advance.
You are returning an Eloquent Builder object from this route:
Route::get('contacts', function () {
return Contact::latest()->orderBy('created_at', 'desc');
});
You can not return this, the framework does not know what to do with this object, you should be executing the query and returning the result:
return Contact::latest()->get();
Then this Collection will get serialized to JSON.
I know this is old, but you could also return dd($variable) to view the content of the returned variable without returning ->first() or ->get().
This could be useful for debugging.

how to send data from Blade view to controller in laravel to preform a post request

I am trying to favorite and unfavorite posts and insert it in favorites table if clicked and if clicked again it deletes it from favorites table i put my routes in web.php file
the functions in the controller which should be called in the route are not called i insert there dd() method to test it so i am guessing the problem is in the form action and not sending the data
<body>
...
#foreach ($posts as $post)
<div class="column">
#if ($post->showstar == true)
<form action="/favorites/delete" method="post">
<span class="foo fa fa-star checked"></span>
</form>
#endif
<h2>{{$post->title}}</h2>
<img src={{$post->url}} >
</div>
#endforeach
</body>
<script>
$(document).ready(function () {
$("form").on("click", ".foo", function () {
if ($(this).hasClass("checked")) {
$(this).removeClass("checked");
} else {
$(this).addClass("checked");
}
});
});
</script>
Controller:
class FavoritesController extends Controller
{
public function index()
{
return view('Favorites', ['favs' => Favorite::where('user_id', '1')->get()]);
}
public function view(Request $request)
{
dd("hello");
$fav = new Favorite();
$fav->user_id = $request->get('userid');
$fav->post_id = $request->get('postid');
$fav->save();
}
public function delete(Request $request)
{
dd("bye");
$fav = new Favorite();
$dfav = $fav->where('id', $request->id);
$dfav->delete();
return view('favorites');
}
public function fetch(Request $request)
{
$fav = new Favorite();
$favs = $fav->where('user_id', $request->user_id);
return view('favorites', compact('favs'));
}
}
Routes:
Route::post('/favorites', 'FavoritesController#view');
Route::post('/favorites/delete', 'FavoritesController#delete');
Route::post('/favorites/fetch', 'FavoritesController#fetch');
You could always try the plain and simple html form submit.
<form action="/favorites/delete" method="post">
#csrf
<input type="hidden" name="id" value="{{ $post->id }}">
<button>
<span class="foo fa fa-star checked"></span>
</button>
</form>
This way you can send the hidden input, post id in your case, to the controller and it will delete it.
You need a similar function ajax, to send data to a controller:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url:'youUrl',
data:{'youData':"YourValueData"},
type:'post',
success: function (response) {
alert(response);
},
error: function(x,xs,xt){
alert(x);
}
});

laravel ajax insert data form comment success only in firts column

Sory my english is not good, I have a problem with comment input form in my program. the comment field in the process will only succeed if the filled column is the top column. if the comment field other than the above will fail. please enlighten him
this is a successfull process in first column comment
but if I write in the comment field other than the above will fail
token and field with_id same as comment column above, whereas value from barengan_id if in inspect element differ its contents. and also comment field so empty value
and this is my code
my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Barengan;
use App\BarenganComment;
use App\User;
class CariBarenganCommentController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function store(Request $request,Barengan $id)
{
$data = [
'user_id' => auth()->id(),
'barengan_id' => $id->id,
'comment' => $request['comment'],
];
return BarenganComment::create($data);
}
public function destroy(Barengan $barengan_id,$id)
{
BarenganComment::destroy($id);
}
}
And this my form in view
<div id="form">
<form method="post" data-toogle="validator" class="form-horzontal">
{{ csrf_field() }}
{{method_field ('POST')}}
<input type="hidden" name="id" id="id">
<input type="hidden" name="barengan_id" value="{{$d->id}}" id="barengan_id">
<div class="styled-input">
<input class="input inputkoment" type="text" placeholder="Tulis Komentar ..." name="comment" id="comment">
<span></span>
<button type="submit" class="btn btn-default pull-right btn-custom-komen"><i class="fa fa-chevron-circle-right"></i></button>
</div>
</form>
</div>
<script src="{{asset('js/jquery-1-11-0.js')}}"></script>
<script>
function deleteComment(id) {
var popup = confirm("apakah anda yakin akan menghapus data?");
var csrf_token = $('meta[name="csrf-token"]').attr('content');
if(popup == true){
$.ajax({
url: "{{ url('caribarengancomment')}}/"+id,
type: "POST",
data: {'_method': 'DELETE','_token': csrf_token
},
success: function(data) {
$("#contact-table").load(" #contact-table");
$('#alert-success').html('show');
},
error: function () {
alert("Opppps gagal");
}
})
}
}
$(function () {
$(document).on('submit','#form form',function (e) {
if (!e.isDefaultPrevented()) {
var barenganId = $('#barengan_id').val();
console.log(barenganId);
url = "{{ url('caribarengan')}}/" + barenganId + "/comment";
// url= '{{route('caribarengancomment.store',$d)}}';
$.ajax({
url: url,
type: "POST",
data: $('#form form').serialize(),
success: function(data) {
$("#contact-table").load(" #contact-table");
$('#alert-success').html('show');
},
error: function () {
alert('Oops! error!');
}
});
return false;
}
});
});
</script>
and my model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BarenganComment extends Model
{
protected $fillable = ['user_id','barengan_id','comment'];
public function user()
{
return $this->belongsTo(User::class);
}
public function barengan()
{
return $this->belongsTo(Barengan::class);
}
}
I am very tired these days stack here :(
you use multiple forms on page? look like id`s of inputs conflict.
try this way
<form method="post" data-toogle="validator" class="form-horzontal" data-barengan="{{$d->id}}">
...
if (!e.isDefaultPrevented()) {
var barenganId = $(this).data('barengan');

Fileupload from AngularJs to laravel(Call to a member function getClientOriginalExtension() on string)

I am getting an issue with the file upload from angular to laravel 5.2. Throws an error of "Call to a member function getClientOriginalExtension() on string"
Routes:
Route::get('fileupload', array('as' => 'fileupload.index', 'uses'=>'FileController#index'));
Route::post('filehandler/submit', array('as' => 'filehandler.submit', 'uses' => 'FileController#store'));
View:
<!DOCTYPE html>
<html ng-app="myApp">
<div ng-controller="fileCtrl">
<form ng-submit="addList1()" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="text" name="text" ng-model="info.text">
<input type="file" name="file" ng-model="info.file" id="uploads" required>
<button type="submit">Submit</button>
</form>
<script type="text/javascript" src="{{URL::to('/')}}/angular/bower_components/jquery/dist/jquery.js"></script>
<script type="text/javascript" src="{{URL::to('/')}}/angular/bower_components/angular/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-animate.js"></script>
<script type="text/javascript" src="{{URL::to('/')}}/angular/bower_components/angular-bootstrap/ui-bootstrap-tpls.js"></script>
<script type="text/javascript" src="{{URL::to('/')}}/angular/js/all.js"></script>
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use View;
use File;
use DB;
class FileController extends Controller
{
public function index()
{
return View('file');
}
public function store(Request $request)
{
$input = Input::all();
$destinationPath = 'uploads'; // upload path
$file = $input['file'];
$extension = $file->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension;
$file= Input::file('file')->move($destinationPath, $fileName);
print_r($file);
exit;
}
}
My JS file(all.js)
angular.module('myApp',[])
myApp.service('data', function ($http) {
var service ={};
service.postFile = function(info){
var promise = $http.post('filehandler/submit', info);
promise.then(function(response){
angular.extend(info, response.data);
});
return promise;
};
return service;
})
.controller('fileCtrl', function($scope, data) {
$scope.info = {
"text": "",
"file": []
};
$scope.addList1 = function(form){
data.postFile($scope.info).then(function(response){
console.log("hello", $scope.info);
});
};
})
It is working fine without angular, when I am implement through angular it shows error in my controller. In FileController I am getting an error "Call to a member function getClientOriginalExtension() on string". Can anyone please help me it to fix this out, Thanks in advance
In order to get the uploaded file you need to call Request's file() method.
Replace
$file = $input['file'];
with
$file = $request->file('file');

Categories