Store data in PostgreSQL using Laravel and Vue.js - laravel

I am new to Vue.js and would like to know more about it, so I tried this video. I followed all code but cannot store data in the database and I get this error:
TodoController.php
public function store(Request $request)
{
$todo = Todo::create($request->all());
$todo->create();
return $todo;
}
Post.php
protected $fillable = ['title', 'completed'];
TodoComponent.vue
<form #submit.prevent="saveData">
<div class="input-group mb-3">
<input v-model="form.title" type="text" class="form-control form-control-lg" aria-label="Recipient's username" aria-describedby="button-addon2">
<div class="input-group-append">
<button class="btn btn-success" type="submit" id="button-addon2">Add List </button>
</div>
</div>
</form>
Vue method
methods:{
saveData(){
let data = new FormData();
data.append('title', this.form.title)
axios.post('/api/todo', data)
}
},

Related

Axios returning HTML in response instead of data

I want to ask for help regarding Axios' response to my POST request in the login route via Laravel. It returns HTML of the homepage in data when it authenticated the user (or it finds the user in the database). Please see the response screenshot below:
May I just ask for the solution to my problem? Here are the necessary codes and the versions that I am using:
Tools
VueJS: v3.0.5
Axios: 0.19
Laravel: 5.8
Codes
Login.vue (script)
import axios from 'axios'
export default {
data() {
return {
csrfToken: '',
loginObj: {
username: '',
password: '',
remember: false,
},
message: '',
}
},
created() {
this.csrfToken = document.querySelector('meta[name="csrf-token"]').content;
},
methods: {
signIn() {
console.log(this.loginObj)
axios.post('login', this.loginObj).then(res => {
console.log(res)
})
.catch(error => {
console.log(error.response)
})
}
}
}
Login.vue (template)
<div class="card shadow-lg border-0 rounded-lg mt-5">
<div class="card-header bg-orange"><h3 class="text-center my-4">Hello!</h3></div>
<div class="card-body p-0">
<div class="row">
<div class="col-lg-6 d-none d-lg-block">
<div class="login-image-wrap text-center">
<img src="/img/ahrs_logo_trans.png" class="login-img" alt="AKB Logo">
</div>
</div>
<div class="col-lg-6">
<div class="p-5">
<div class="text-center">
<h1 class="h4 text-gray-900 mb-4">Sign In</h1>
</div>
<form name="loginForm" #submit.prevent="signIn">
<input type="hidden" name="_token" :value="csrfToken">
<div class="form-group">
<label class="small mb-1" for="inputUsername">Username</label>
<input class="form-control py-4" v-model="loginObj.username" id="inputUsername" type="text" placeholder="Enter username" required autofocus>
</div>
<div class="form-group">
<label class="small mb-1" for="inputPassword">Password</label>
<input class="form-control py-4" v-model="loginObj.password" id="inputPassword" type="password" placeholder="Enter password" required>
</div>
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" v-model="loginObj.remember">
<label class="form-check-label text-small" for="remember">
Remember Me
</label>
</div>
</div>
<div class="form-group d-flex align-items-center justify-content-between mt-4 mb-0">
<a class="small" href="password.html">Forgot Password?</a>
</div>
<hr />
<div>
<button type="submit" class="btn bg-yellow btn-block font-weight-bold">LOGIN</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
LoginController.php
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
// override in the AuthenticatesUsers function username()
public function username()
{
return 'username';
}
Thank you for your help.
You will probably need to tell Laravel that you want to return the User as JSON if it's an ajax request.
You can do this by adding the following to your LoginController:
protected function authenticated(Request $request, $user)
{
if ($request->ajax()) {
return $user;
}
}
You may also need to set the X-Requested-With header that is usually set in the default bootstrap.js file that comes with Laravel so that Laravel knows it's an ajax request:
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
Obviously, if this line is already there and you're still including the bootstrap file in your bundle you can ignore this.

laravel 6 : Call to a member function store() on null

I am trying to attach a file to a blog type post. For this i have an file field and 2 buttons, one saves the fields to the database and the other uploads the file. standalone the file upload works as intended. However in the form i get Call to a member function store() on null. I have changed the menthod from put to post, but that doesnt seem have any effect.
Below my post forms and the function in the controllers.
The Form:
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">New/Edit Blog</div>
<div class="card-body">
#if($data)
<form … action = "{{Route ('post.update', $data->_id)}}" method="post", enctype = 'multipart/data'>
#csrf
#method('POST')
<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="shorttext">Shorttext:</label>
<input type="text" class="form-control" name="shorttext" value = "{{$data->shorttext}}" >
</div>
<div>
<input id="x" type="hidden" name="content" value ="{{$data->content}}">
<trix-editor input="x" ></trix-editor>
</div>
<div class="form-group">
<label for="created_by">Created By:</label>
<input type="text" class="form-control" name="created_by" value = "{{$data->created_by}}" readonly>
</div>
<input type="file" name="attachment" enctype="multipart/form-data"/>
<p align="center">
<input type="submit" btn btn-primary class="btn btn-primary" id="save" name="action" value="save">
<input type="submit" btn btn-primary class="btn btn-primary" id="upload" name="action" value="upload">
The functions in the controller:
Store:( this one is the function that determines which button is pressed)
public function store(Request $request, $_id = false, $attachment = false){
//check which submit was clicked on
if($request->action == 'upload'){
//
$this->upload($request);
return redirect()->route('home');
} elseif($request->action == 'save') {
//echo 'save pressed';
//run function save all form fields
$this->update($request, $_id);
return redirect()->route('home');
} else {echo "error";}
}
Upload function:
function upload(Request $request){
$path = $request->file('attachment');
// $original = $request->file('attachment')->getClientOriginalName();
$path->store('/public');
Update function:
public function update (Request $request, $_id){
//$this->upload($request);
/*
$path = $request->file('attachment');
$path->storeas('/public','123'); */
$data = post::findOrFail($_id);
$data->title = $request->title;
$data->content = $request->content;
$data->shorttext = $request->shorttext;
$data->created_by = $request->created_by;
$data->text3 = $request->text3;
$data->attachment = $request->attachment;
$data->save();
if($data){
return redirect()->route('home');
}else{
return back();
}
}
The route is:
Route::post('/post/update/{_id}', 'PostController#store')->name('post.update');
As mentioned, the save function in the complete form works. In a standalone form ( and a standalone controller) the upload works (and i can, if i wish, manipulate the filename), but how do i bring the 2 together? At first i thought it was because the update form had a PUT method, but changing everything to post doesnt seem to have any effect and i still get the Null error.
For completeness the standalone solution:
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Te7aHoudini\LaravelTrix\Pipes\AttachmentInput;
class UploadController extends Controller
{
//
function upload(Request $req){
$path = $req->file('attachment');
$original = $req->file('attachment')->getClientOriginalName();
$path->storeas('/public',$original);
echo $original;
}
}
The standalone form:
<html>
<head>
<title>Upload</title>
</head>
</html>
<form action="upload" method="POST" enctype="multipart/form-data">
<input type="file" name="attachment" />
#csrf
<button type="submit">file upload</button>
</form>
In your form element Change enctype = 'multipart/data' to enctype="multipart/form-data"
<form … action = "{{ Route ('post.update', $data->_id) }}" method="post", enctype="multipart/form-data">
Hope this solves your problem.

sending ajax data to a route to call a controller method

I'm trying to pass ajax data to a "settings/addsection/{class_id}" route with parameter so as to call a controller method to log on laravel log file. but logging does not work. So the ajax didn't send data to the route. How do I fix this?.. Note that the $class_id which i passed to the hidden input has value as i have queried it from the database.
JAVASCRIPT
<script>
document.addEventListener('DOMContentLoaded' , function(){
var add = document.getElementById('addSection');
add.addEventListener('submit' , function(e){
e.preventDefault();
var class_id = document.getElementById('class_id').value;
var section = document.getElementById('name').value;
var token = document.getElementsByName('_token')[0].value;
var data = {
name:section,
_token:token
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'settings/addsection/' + class_id, true);
xhr.setRequestHeader('Content-Type' , 'application/json');
xhr.send(JSON.stringify(data));
})
})
</script>
HTML
form id = "addSection" method="POST" action=" {{ url('settings/addsection/' .$class_id)}}">
#csrf
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">{{ __('add section') }}</label>
<div class="col-md-6">
<input id="name" name="name" type="text" class="form-control #error('name') is-invalid #enderror" value="{{ old('name') }}" autocomplete="name" autofocus placeholder="A,B,C...Z">
<input type="hidden" id = "class_id" value = "{{$class_id}}">
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary btn-block">
{{ __('Add add section') }}
</button>
</div>
</div>
</form>
this is the web.php where the routes are
Route::middleware(['auth' , 'admin'])->group(function(){
Route::prefix('settings')->group(function(){
Route::post('addsection/{class_id}' , 'SectionController#store');
});
});
SectionController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Section;
class SectionController extends Controller
{
public function store(Request $request , $class_id){
//do stuff here
Log::info(' it works');
}
}
I worked around this problem by changing this
xhr.open('POST', 'settings/addsection/' + class_id, true);
to
xhr.open('POST', "{{url('settings/addsection/')}}" + '/' +class_id, true);

How to update specific row using modal Laravel 5.8

I am trying to update a specific row using modal. However I don't have any idea how to pass the value of the row id to the route parameter.
Here's the update form.
<form action="{{route('subcategory.update', 'idhere')}}" method="POST">
#method('PATCH')
#csrf
<div class="modal-body">
<label for="editname">New sub-category name:</label>
<input type="text" name="editname" id="editname" class="form-control">
<input type="text" name="editid" id="editid" value="" hidden>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button class="btn btn-primary" type="submit">Save changes</button>
</div>
</form>
Edit button
<button class="btn btn-secondary btn-sm" data-myid="{{$item->id}}"
data-mytitle ="{{$item->name}}"
data-target="#editsub" data-toggle="modal">Edit</button>
And here's the controller
public function update(Request $request, Subcategory $subcategory)
{
// return $request;
Subcategory::where('id',$request->editid)->update([
'name' => $request->editname
]);
return back();
}
When you pass an id here and if your model name is subcategory.php you will get the db record in your controller.
<form action="{{route('subcategory.update', $subcategory )}}" method="POST">
Or you can do following too
<form action="{{route('subcategory.update', $subcategory->id )}}" method="POST">
Your route should have {subcategory} in it for eager loading. After that you can do following in your code.
public function update(Request $request, Subcategory $subcategory)
{
//variable $subcategory has the db record
$subcategory->update(['name' => $request->only('editname')]);
return back();
}
If I understand it correctly, you can store the item id in
<input type="text" name="editid" id="editid" value="{$item->id}" hidden>
And since you are using POST request, you can easily get the item id from the request.
Like the one in your post:
$request->input('editid');
Please try first to pass id in input box hidden field

move() function not working in laravel 5.2 while editing/updating pictures

I have a founder page where the user can upload name, information and image of the founder.
In my view when I edit pictures and upload a new one, the name of the pictures gets stored in the database but the image is not being uploaded. There must be some problem in my controller but i can't seem to find out what. Any help would be appreciated.
Below are my model, controller and view.
Founder Model
class Founder extends Model
{
protected $fillable = ['name','information', 'image'];
public function getImageAttribute()
{
if (! $this->attributes['image']) {
return 'noimage.jpg';
}
return $this->attributes['image'];
}
public function getCreatedAtAttribute($date)
{
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d');
}
public function getUpdatedAtAttribute($date)
{
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d');
}
Founder Controller
public function update(Request $request, $id)
{
$founder = Founder::find($id);
$input = $request->all();
if($file=$request->file('image'))
{
$name = $file->getClientOriginalName();
$file->move('/images/', $name);
$input['image']= $name;
}
$founder->update($request->all());
return redirect()->route('founder.view');
}
Founder View Edit Form
<form class="form-horizontal" action="/founders/{{$founder->id}}" method="POST">
{{csrf_field()}}
<input type="hidden" name="_method" value="PUT">
<div class="form-group">
<label class="col-md-12">Name</label>
<div class="col-md-12">
<input type="text" name="name" class="form-control" value="{{$founder->name}}">
</div>
</div>
<div class="form-group">
<label class="col-md-12">Information</label>
<div class="col-md-12">
<textarea class="form-control" name="information" rows="3" value="{{$founder->information}}">{{$founder->information}}</textarea>
</div>
</div>
<div class="form-group">
<label class="col-md-12">Change Image</label>
<div class="col-md-12">
<input type="file" name="image" class="form-control" value="{{$founder->image}}">
</div>
</div>
<button type="submit" name="submit" class="btn btn-success waves-effect waves-light m-r-10">Submit</button>
</form>
Try to use rename:
rename ('current/path/to/foo', 'new/path/to/foo');
Documentation: http://php.net/rename
UPDATE:
Or use variable $destinationPath:
$file->move($destinationPath, $chooseYourFileName);
Use This Method This Will Work 100%
if($request->hasFile('filename')){
$file = $request->filename;
$file_new_name = $file->move("upload/posts/", $file->getClientOriginalName());
$post->filename = $file_new_names;
}
Remember filename is your < img name="filename" >

Resources