How can I get the api_token in the controller? - laravel

I have this Vuejs Code:
axios.get('/api/electronic_collection?page='+this.currentPage+'&api_token='+App.apiToken)
.then(response => {
this.posts = response.data.data.data;
this.total = response.data.data.last_page;
this.currentPage = response.data.data.current_page;
this.rowsQuantity = response.data.data.total;
});
How you can see I am seding the api_token because it connects to an API Restful but what I want to do it's that I need to get this api_token in the controller.
My controller is like this:
public function index(Request $request)
{
but I'd like to get the api_token here, how can I do that I mean $_GET['api_token'] is it like this?
}

The query string is an input source. You can ask the Request for this input:
$request->input('api_token')
Laravel 8.x Docs - Requests - Retrieving Input - Retrieving and Input value input

You can get it off the $request object
public function index(Request $request)
{
$apiToken = $request->api_token;
//OR
$apiToken = $request->query('api_token');
}

Related

How to use parameter from function to create an URL? Laravel Routing

I'm sending an URL hashed and when i get it i have to show a view on Laravel, so i have those functions on the controller and also some routes:
This are my routes:
Route::post('/sendLink', 'Payment\PaymentController#getPaymentLink');
Route::get('/payment?hash={link}', 'Payment\PaymentController#show');
And this are the functions i have on my controller:
public function getPaymentLink (Request $request){
$budgetId = $request['url.com/payment/payment?hash'];
$link = Crypt::decryptString($budgetId);
Log::debug($link);
//here to the show view i wanna send the link with the id hashed, thats why i dont call show($link)
$view = $this->show($budgetId);
}
public function show($link) {
$config = [
'base_uri' => config('payment.base_uri'), ];
$client = new Client($config);
$banking_entity = $client->get('url')->getBody()->getContents();
$array = json_decode($banking_entity, true);
return view('payment.payment-data')->with('banking_entity', $array);
}
And this is getting a "Page not found" message error.
What i want to to is that when i the client clicks on the link i send him that has this format "url.com/payment/payment?hash=fjadshkfjahsdkfhasdkjha", trigger the getPaymentLink function so i can get de decrypt from that hash and also show him the view .
there is no need to ?hash={link} in get route
it's query params and it will received with $request
like:
$request->hash
// or
$request->get('hash')
You need to define route like this:
Route::get('/payment/{hash}', 'Payment\PaymentController#show');
You can now simply use it in your Controller method like below:
<?php
public function getPaymentLink (Request $request,$hash){
$budgetId = $hash;
// further code goes here
}

dd() not working in vue-laravel project axios call.Is it possible to use dump in axios call?

I am using vue with laravel.but my save function not working. So I tried to dump and die the request object but I can't see the request object in the preview. it is blank.
protected function save()
{
$request = Request::all();
dd($request);
$suggestion = new Suggestion();
$suggestion->connection_id = $request['connection_id'];
$suggestion->company_id = $request['company_id'];
$suggestion->module = $request['module'];
$suggestion->description = $request['image'];
$suggestion->save();
return 'success';
}
the axios call is
axios.post('suggestion/save', this.post).then(response => {
this.$swal({
title: 'Success',
text: response.data.message,
type: 'success',
confirmButtonText: 'OK',
});
this.$router.push('/suggestion-list');
})
There are multiple Request classes in Laravel, One thing you can try is the following,
public function controllerFunction()
{
dd(request()->all());
$suggestion = new Suggestion();
$suggestion->connection_id = $request['connection_id'];
$suggestion->company_id = $request['company_id'];
$suggestion->module = $request['module'];
$suggestion->description = $request['description'];
$suggestion->save();
return 'success';
}
So irrespective of your class, the request() function will bring up the appropriate object.
If you get to dump the request then you can confirm that the request is hitting the appropriate controller function, otherwise, the request is going somewhere else. check the network tab in chrome for more details.
Also, make sure you have the appropriate Request class in the use statements.
The correct Request class usage is like following
use Illuminate\Http\Request;
Add request to your function
also add 'use Illuminate\Http\Request'
use Illuminate\Http\Request
public function myFunction(Request $request)
{
dd($request->all());
...
}
hey you can use print() or print_r() to check result
and make sure your this.post has data or not

How to get redirect url in Vuejs from Laravel/Passport

I'm building a simple login in Vue.js where my backend in laravel/passport for authentication method. Before implementing passport I was having a manual login controller which get the redirect url from session something like this:
Suppose my Routes was Route::post('/login', 'LoginController#postLogin) now in the controller I was computing something like this:
public function postLogin(Request $request)
{
$this->validate($request, User::$login_validation_rules);
$data = $request->only('email', 'password');
$intended_url = Session::get('url.intended', url('/'));
Session::forget('url.intended');
// Authentication codes
return $intended_url, $user;
}
Now I was taking this in Vue file like this:
axios.post('/login', postData).then(response => {
// computation of objects
window.location.href = '/dashboard';
})
Now my url as I'm using Laravel\passport has been changed to axios.post('/oauth/token', postData)
Can someone guide me how to add intended_url to this response, Is it possible to get in same axios request or I have to call another axios request
You can set the return to a Json object that's easy to parse and Axios should be able to be set up to automatically parse it.
public function postLogin(Request $request)
{
$this->validate($request, User::$login_validation_rules);
$data = $request->only('email', 'password');
$intended_url = Session::get('url.intended', url('/'));
Session::forget('url.intended');
// Authentication codes
return \Response::json([ 'url' => $intended_url, 'user' => $user], 200);
}
This will create a Json object with the pertinent information and pass it with the correct headers. in JS it should be something similar to this:
axios.post('/login', postData)
.then(
response => {
let JsonObj = JSON.parse(response.body)
// computation of objects
window.location.href = JsonObj.url;
}
)
you may have to do some tests to see what response is returning and go from there.

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.

Passing route parameter to controller Laravel 5

I'm trying to pass a route parameter to controller, but I get this error : Argument 2 passed to App\Http\Controllers\JurnalController::store() must be an instance of App\Http\Requests\JurnalRequest, none given
Below are the codes ..
Route :
Route::get('/edisi/{id}', 'JurnalController#store');
Controller :
public function store($id, JurnalRequest $request) {
$input = $request->all();
//Input PDF
if ($request->hasFile('file')) {
$input['file'] = $this->uploadPDF($request);
}
$jurnal = Edisi::findOrFail($id)->jurnal()->create($input);
return redirect('jurnal');
}
So my question is how to pass the route parameter properly ? Thank you
new routes :
Route::get('/', function () {
return view('pages/home');
});
Route::group(['middleware' => ['web']], function () {
Route::get('edisi', 'EdisiController#index');
Route::get('edisi/create', 'EdisiController#create');
Route::get('edisi/{edisi}', 'EdisiController#show');
Route::post('edisi', 'EdisiController#store');
Route::get('edisi/{edisi]', 'EdisiController#edit');
Route::patch('edisi/{edisi}', 'EdisiController#update');
Route::delete('edisi/{edisi}', 'EdisiController#destroy');
});
Route::get('/edisi/{id}', 'JurnalController#storejurnal');
Route::group(['middleware' => ['web']], function () {
Route::get('jurnal', 'JurnalController#index');
Route::get('jurnal/create', 'JurnalController#create');
Route::get('jurnal/{jurnal}', 'JurnalController#show');
Route::post('jurnal', 'JurnalController#storejurnal');
Route::get('jurnal/{jurnal}/edit', 'JurnalController#edit');
Route::patch('jurnal/{jurnal}', 'JurnalController#update');
Route::delete('jurnal/{jurnal}', 'JurnalController#destroy');
});
new storejurnal method :
public function storejurnal(JurnalRequest $request, $id) {
$input = $request->all();
//Input PDF
if ($request->hasFile('file')) {
$input['file'] = $this->uploadPDF($request);
}
//Insert data jurnal
$jurnal = Edisi::findOrFail($id)->jurnal()->create($input);
return redirect('jurnal');
}
When you are using resource controller, the store method does not accept any other argument except the Request instance. Try changing the method name or remove the second argument. store() method be default accepts post requests not get requests. Either put your route on top of the resource controller or change the method name.
Route::get('/edisi/{id}', 'JurnalController#store');
Route::resource('jurnals', 'JurnalController');
I hope this helps.
The correct format is:
public function store(JurnalRequest $request, $id) {
// your code
}
If you receive an argument such as Missing argument 2 as suggested in your comments, it means that either you aren't generating the routes correctly, or the url doesn't include the id segment.

Resources