Laravel 5 Collecting Post Data - laravel-5

I am having an issue with working with post data.
For example, if i have a simple little form :
<form action='/leads/getpost' method='POST'>
<input type='text' name='Domain'>
<input type='submit' name='submit'>
AND then collect the data and try echo it out :
public function getPost()
{
$formData = Request::all() ;
var_dump($formData);
//
}
I get an error : MethodNotAllowedHttpException in RouteCollection.php line 218:
If i do the same thing using GET it works fine.
I tried to edit the VerifyCsrfToken and added :
protected $except = [ 'leads/getpost'
//
];
Still not working.

Try This
Route:
Route::post('leads/getpost', 'nameofController#getPost');
Controller:
use Request;
public function getPost()
{
$formData = Request::all();
var_dump($formData); // or you could return it to the view
}

Related

Creating default object from empty value using laravel 6 and ajax

i have in an annonces table a multiple images, i want to update multiple images, but it gives me error:
Creating default object from empty value knowing that i tried to transform multipleimage to a given json.in the console it gives me the name of the images to select.
AnnoncesController.php
public function filesUpdate(Request $request,$id)
{
$Annonce=Annonce::find($id);
$data = array();
if($request->hasFile('images'))
{
foreach($request->file('images') as $file)
{
$path = $request->images->store('annonces');
$Annonce->images = $path;
array_push($data,$path);
}
}
$Annonce->images = json_encode($data);
$Annonce->save();
return Redirect::to("annonces")
->withSuccess('Great! file has been successfully uploaded.');
}
web.php
Route::post('annonces/filesUpdate','AnnoncesController#filesUpdate');
details.blade.php
<form method="post" action="{{url('annonces/filesUpdate')}}" enctype="multipart/form-data"
class="dropzone" id="dropzone">
<input type="hidden" name="_method" value="PUT">
{{ csrf_field() }}
</form>
<script type="text/javascript">
Dropzone.options.dropzone =
{
maxFilesize: 12,
renameFile: function(file) {
var dt = new Date();
var time = dt.getTime();
var images = time+file.name
console.log(time+file.name);
return images;
},
acceptedFiles: ".jpeg,.jpg,.png,.gif",
addRemoveLinks: true,
timeout: 50000,
success: function(file, response)
{
console.log(response);
},
error: function(file, response)
{
return false;
}
};
</script>
You are not passing the id as route parameter in the form action so the $id value received in filesUptate method in controller will be null. You have to pass the $Annonce->id as route parameter via form action
//When you send this view as response from edit method you need to pass
//either $Annonce object or at least the $Annonce->id as $AnnonceId to the view
//If you pass the entire $Annonce object then append $Annonce->id as below
//to the form action or replace it with $AnnonceId if you are passing only
//$AnnonceId from the edit method of the controller
<form
method="post"
action="{{url('annonces/filesUpdate/' . $Annonce->id)}}"
enctype="multipart/form-data"
class="dropzone" id="dropzone"
>
<input type="hidden" name="_method" value="PUT">
{{ csrf_field() }}
</form>
The error probably arises as you are trying to call store method on array.
Try the below
public function filesUpdate(Request $request,$id)
{
$Annonce=Annonce::findOrFail($id);
$data = array();
if($request->hasFile('images'))
{
foreach($request->file('images') as $file)
{
//Trying to call store on an array here
//$request->images is not an instance of UploadedFile
//$path = $request->images->store('annonces');
//$file is an instance of UploadedFile
//so you can call store method on it
$data[] = $file->store('annonces');
}
}
$Annonce->images = json_encode($data);
$Annonce->save();
return Redirect::to("annonces")
->withSuccess('Great! file has been successfully uploaded.');
}
You can also use $casts property to let Laravel handle the casting of images attribute automatically
class Annonce extends Model
{
protected $casts = [ 'images' => 'array'];
}

how do i pass data value to another page via link in laravel?

i am trying to make a list of locations that you can rent. but to rent the place you need to fill in some information. to fill in this information you excess another page. how do i make it so laravel knows the page belongs to a certain location
this is what ive done now but i keep getting the error:
Call to undefined method App\Reservation::location()
as soon as i have filled in the fields of information
this is the blade file that links to the the create reservation file
#foreach
($locations as $location => $data)
<tr>
<th>{{$data->id}}</th>
<th>{{$data->name}}</th>
<th>{{$data->type}}</th>
<th><a class="btn" href="{{route('Reservation.index', $data->id)}}">rent</a></th>
</tr>
#endforeach
this is the create reservations blade
<form action="{{ route('location.store') }}" method="post">
#csrf
<label>title</label>
<input type="text" class="form-control" name="name"/>
<label>type</label>
<select>
<option value="0">klein</option>
<option value="1">groot</option>
</select>
<button type="submit" class="btn">inschrijven</button>
</form>
this is what the location controller looks like
public function store(Request $request)
{
$location = new Reservation;
$location->name = $request->get('name');
$location->type = $request->get('type');
$location->location()->associate($request->location());
$location->save();
return redirect('/location');
}
and the relationships in my models should also work
class Reservation extends Model
{
public function locations()
{
return $this->belongsTo('Location::class');
}
}
class Location extends Model
{
public function reservations()
{
return $this->hasMany('Registration::class');
}
}
ive been stuck at this all day and i really dont know where to look anymore
The error you are getting is because of the wrong function name, you are calling location, while it is locations.
public function locations(){}
&
$location->location()->associate($request->location());
and you can pass the variable as a query parameter, you'll need to pass this data as an array in your blade file.
Web.php
Route::get('/somewhere/{id?}, function(){
//do something
})->name('test');
Blade
route('test', ['id' => $id]);
Controller Method
public function store(Request $request, $id) //Adding the query parameter for id passed in Route.
{
$location = new Reservation;
$location->name = $request->get('name');
$location->type = $request->get('type');
$location->location()->associate($id);
$location->save();
return redirect('/location');
}

VueJs & Laravel. I can't send an excel file with Vuejs and FileReader

I would like to load an excel file to send it with axios to Controller and Maatwebsite\Excel for an Import.
The import part in Controller is working when i use Php from blade, i have a problem when sending from my Vuejs Component. I can't Read the Excel File. or Maybe i can't read it in Controller.
This is my code :
<template>
<input type="file" #change="checkFile" />
<button #click="importExcel()">Import File</button>
</template>
<script>
//In method
checkFile(e) {
var files = e.target.files || e.dataTransfer.files;
console.log('#', files); // The file is in console
if (!files.length)
return;
this.createFile(files[0]);
},
createFile(file) {
var reader = new FileReader();
var vm = this;
reader.readAsDataURL(file)
vm.ex.excel=file; // my ex.excel object contain File
},
importExcel: function () {
var formData = new FormData();
formData.append("file", this.ex.excel);
axios.post('/importExcel', formData)
},
</script>
So in Controller, i use this code when i'm using php (working)
public function importExcel(Request $request)
{
if($request->hasFile('import_file')){
Excel::import(new UsersImport, request()->file('import_file'));
}
return back();
}
When i try this code for axios. i have an error :
public function importExcel(Request $request)
{
Excel::import(new UsersImport, $request->excel);
return back();
}
Error: No ReaderType or WriterType could be detected
Console.log(file) in image
UPDATE: In controller i added
$a = $request->excel;
dd($a);
result in : null
<template>
<input type="file" ref="file" #change="checkFile" />
<button #click="importExcel()">Import File</button>
</template>
<script>
//In method
{
...
createFile(file) {
this.ex.excel = this.$refs.file.target.value.files[0]
}
...
}
</script>
<?php
...
public function importExcel(Request $request)
{
Excel::import(new UsersImport, $request->file('file'));
return back();
}
...
looks like the mime-type is missing, try add the mime-type together with your HTTP POST ...

post method on two actions within same controller in laravel

Following is my route file i.e web.php
Route::post('finddomainname','DomainController#finddomainname')->name('finddomainname');
Route::post('registerdomains','DomainController#registerdomains')->name('registerdomains');
Following is the code on my DomainController for both the actions used,
public function finddomainname(Request $request)
{
$this->validate($request,
['searchdomaintxt'=>'required',
'searchdomainext'=>'required']);
$searchdomaintxt = $request->input('searchdomaintxt');
$searchdomainext = $request->input('searchdomainext');
$domainname="";
if($searchdomaintxt && $searchdomainext)
{
foreach($searchdomainext as $ext)
{
$domainname.=$searchdomaintxt.".".$ext.",";
}
//dd($domainnames);
$domainnames= rtrim($domainname,',');
$response=$this->soap->multidomainsearch($domainnames);
$result=$response['RESPONSE']['DOMAINSEARCH'];
//dd($result);
if($result){
//return redirect()->action('searchresults', array('response' => $result));
return view('domain.searchresults',['response'=>$result]);
}
else
{
return view('domain.searchresults',['response'=>'']);
}
}
}
Following is the second action on which control come after submitting data
public function registerdomains(registerDomainsValidation $request)
{
$domains=$request->input('selecteddomains');
$selectedyear =$request->input('selectedyear');
$domaincontactid=\Session::get('domaincontactid');
$alldomains='';
foreach($domains as $domain)
{
$alldomains.=$domain.",";
}
$alldomains=rtrim($alldomains,',');
$response=$this->soap->registerdomains($alldomains,$domaincontactid,$selectedyear);
return view('domain.searchresults',['response'=>$response]);
}
but when i submit data it will show me this error
protected function methodNotAllowed(array $others)
{
throw new MethodNotAllowedHttpException($others);
}
You are trying to access your POST route using a GET request, that's why you are receiving a MethodNotAllowedHttpException. To solve this issue, make sure that your <form></form> tag contains the appropriate method attribute.
<form action="{{ YOUR_URL }}" method="POST">
...
</form>
Or if you want to perform the request inside your controller, you can use Guzzle to send http requests. In your controller you can do:
use GuzzleHttp\Client;
$client = new Client();
$response = $client->request('POST', 'YOUR_URL', [
'form_params' => [
'foo' => 'bar'
]
]);

Laravel Controller another function is being called

I'm getting
ErrorException in ProjectController.php line 41: Trying to get
property of non-object
I am calling delete_project() inside my controller but it seems Laravel is also calling the get_project($variable_here) method
ProjectsController
public function get_project($slug_name){
$project = Project::where('slug_name', $slug_name)->first();
if ($project->user_id == Auth::user()->id) {
return view('project', ['project' => $project]);
}else {
return redirect('console');
}
}
public function delete_project(){
}
Web routes
Route::get('/console', 'HomeController#index');
Route::get('project/{slug_name}', 'ProjectController#get_project');
Route::get('get_projects', 'UserController#get_projects');
Route::post('create_new_project', 'ProjectController#create_new_project');
Route::post('/delete_project', 'ProjectController#delete_project');
Solved by adding this input on my form to send a delete request
<input type="hidden" name="_method" value="delete">
And changing the delete_project route so I now have this on my web routes
Route::get('/project/{slug_name}', 'ProjectController#get_project');
Route::delete('/project/{slug_name}', 'ProjectController#delete_project');

Resources