Laravel Auth get disconnected when i try post file - laravel

Hello i'm using Laravel 5.5 and trying to upload a file with vuejs and axios post,
when i upload the file a function is fired but at the server the auth is disconnected don't know why
i've disabled the VerifyCsrfToken because break all my previous axios posts
that's my code at Vuejs :
// update profile picture
uploadProfilePicture(){
let file = event.target.files
let form = new FormData();
form.append('file',file[0]);
axios.post('update-picture',form)
.then((response)=>console.log(responsea.data))
.catch((error)=>console.log(error.response.data))
},
that's my code at server
// update photo profile
public function updatePicture(Request $request)
{
$file = $request->file;
$res = Storage::disk('localLinked')->put('default/user/profile',$file);
$picture = \App\Picture::create([
'link'=>$res
]);
Auth::user()->profilePicture()->delete();
Auth::user()->update([
'idProfilePicture'=>$picture->id
]);
dd('done');
}
the error is that Auth::user() always null
please help i'm stack here
Thanks

Related

update profile in laravel API for mobile apps

I want to build an api for mobile apps. for now, i want to create an edit profile api. but i dont know how to store an image, if user wants to upload their avatar.
Here is my code:
public function profileedit($id, Request $request){
$users = user::find($id);
$users->name = $request->firstName;
$users->thumbnail = $request->avatar;
$users->save();
$data[] = [
'id'=>$users->uid,
'name'=>$users->name,
'avatar'=>$users->thumbnail,
'status'=>200,
];
return response()->json($data);
}
how to put the $request->avatar into my project storage, and show it in url form (my project is already uploaded on the server)
The easiest way to store files in Laravel is this.
use Illuminate\Support\Facades\Storage;
public function profileedit($id, Request $request){
//validator place
$users = user::find($id);
$users->name = $request->firstName;
$users->thumbnail = $request->avatar->store('avatars','public');
$users->save();
$data[] = [
'id'=>$users->uid,
'name'=>$users->name,
'avatar'=>Storage::url($users->thumbnail),
'status'=>200,
];
return response()->json($data);
}
but as you probably know, you should run php artisan storage:link command to generate storage shortcut in public directory.
for security reason you can use validator to let only image file store. in this example I limited file to all image types with maximum 4MB size
$request->validate([
'avatar' => 'required|image|max:4096',
]);
for more information these are document links.
File Storage
Validation

How to use a Webhook url with Paystack and send values to Database

I am using https://github.com/iamraphson/vue-paystack in my laravel+vue SPA project. I can receive payments perfectly but now need to hit a webhook url so that I can update database and give value to user. I have set up the route and added the url on my paystack dashboard. What should I do next? How do I get the charge events and other details in my controller method and send to database?
I have tried the following in my controller:
public function payme(Request $request){
//This receives the webhook
//$email = json_decode($input['data']['customer']['email']);
$email = $request->input('data.customer.email');
$bankname = $request->input('data.gateway_response');
//$bankname = json_decode($input['data']['gateway_response']);
$user = User::where('email', $email);
$user->bankname = $bankname;
$user->save();
return response()->json('processed', 200);

How to send PUT request with a file and an array of data in Laravel

I am programing a web app using Laravel as API and Angularjs as frontend. I have a form to update product using PUT method with a array of informations and a file as product image. But I couldn't get the input requests in the controller, it was empty.
Please see the code below :
web.php ( route )
Route::group(['prefix' => 'api'], function()
{
Route::put('products/{id}', 'ProductController#update');
});
My angularjs product service :
function update(productId, data, onSuccess, onError){
var formData = new FormData();
formData.append('imageFile', data.imageFile);
formData.append('image', data.image);
formData.append('name', data.name);
formData.append('category_id', data.category_id);
formData.append('price', data.price);
formData.append('discount', data.discount);
Restangular.one("/products", productId).withHttpConfig({transformRequest: angular.identity}).customPUT(formData, undefined, undefined, {'Content-Type': undefined}).then(function(response) {
onSuccess(response);
}, function(response){
onError(response);
}
);
}
My ProductController update function
public function update(Request $request, $id) {
// Just print the request data
dd($request->all());
}
This is what I see in Chrome inspectmen
Please share your experiences on this problem. Thanks.
what you need is Only normal POST request with new field named _method=put then your code will work normally:
You can't do that, according to this discussion. What you should do instead is to 'fake' the PUT request by using Form Method Spoofing
Try this method:
public update(Request $request, $id)
{
$request->someVar;
$request->file('someFile');
// Get variables into an array.
$array = $request->all();
Also, make sure you're using Route::put or Route::resource for your route.

Attach authenticated user to create

I'm trying to attach the currently logged in user to this request, so that I can save it in the database. Can someone point me in the right direction, please?
public function store(CreateLeadStatusRequest $request)
{
$input = $request->all();
$leadStatus = $this->leadStatusRepository->create($input);
Flash::success('Lead Status saved successfully.');
return redirect(route('lead-statuses.index'));
}
So, I have come up with the following using array_merge, but there must be a better way, surely?
public function store(CreateLeadStatusRequest $request)
{
$input = $request->all();
$userDetails = array('created_by' => Auth::user()->id, 'modified_by' => Auth::user()->id);
$merged_array = array_merge($input, $userDetails);
$leadStatus = $this->leadStatusRepository->create($merged_array);
Flash::success('Lead Status saved successfully.');
return redirect(route('lead-statuses.index'));
}
So you can use Auth Facade to get information of currently logged user.
For Laravel 5 - 5.1
\Auth::user() \\It will give you nice json of current authenticated user
For Laravel 5.2 to latest
\Auth::guard('guard_name')->user() \\Result is same
In laravel 5.2, there is new feature called Multi-Authentication which can help you to use multiple tables for multiple authentication out of the box that is why the guard('guard_name') function is use to get authenticated user.
This is the best approach to handle these type of scenario instead of attaching or joining.
public function store(CreateLeadStatusRequest $request)
{
$input = $request->all();
$userDetails = \Auth::user(); //Or \Auth::guard('guard_name')->user()
$leadStatus = $this->leadStatusRepository->create($input);
Flash::success('Lead Status saved successfully.');
return redirect(route('lead-statuses.index'));
}
Hope this helps.

Laravel unauthorized page when ajax send request

I'm making web based game. The game need to login first, so I use laravel auth::register and auth::login as usual, and add middleware auth to every pages except login&register page.
Then check the game status using smartupdater if ready or not.
$("section").smartupdater({
url : urlCheckStatus,
data : data,
dataType : 'json',
minTimeout: 2000
}, function(response){
var gameStatus = response.data.status;
if(gameStatus === 'start')
{
gameOn();
}
else if(gameStatus === 'active')
{
pleaseWait();
}
else if(gameStatus === 'stop')
{
backToMenu();
}
});
Register and login function
public function register(Request $request)
{
$name = $request->input('username');
$user = new User;
$user->name = $request->input('username');
$user->email = $name.'#abc.com';
$user->password = bcrypt(Carbon\Carbon::now());
$user->grade = $request->input('grade');
$user->numb = $request->input('numb');
$user->save();
Auth::login($user, true);
return redirect('menu');
}
check game status function
public function checkGameStatus()
{
$game_id = Request::input('game_id');
$data = Game::find($game_id);
return response()->json([
'data' => $data
]);
}
But sometimes I was thrown to login page, because error 401 Unauthorized. Trying to console log like the image above.
Thanks
I see you are using Javascript for authorization with Laravel, as per Laravel documentation for API Authentication with Javascript:
If you are using a different JavaScript framework, you should make
sure it is configured to send the X-CSRF-TOKEN and X-Requested-With
headers with every outgoing request.
Can you ensure X-CSRF-TOKEN and X-Requested-With are always present in your headers.

Resources