Cookie::get returns null, laravel 5.4 - laravel

I'm trying to cookie user login values,
I grouped in route like this:
Route::group(['middleware' => ['admin']], function () {
Route::post('/admin/addArticle', [
'as' => 'article_save', 'uses' => 'AdminController#saveCover'
]);
Route::get('/admin/introduction', [
'as' => 'introduction', 'uses' => 'AdminController#introduction'
]);
});
AdminController:
$cookie = Cookie::forever('admin', $admin);
Cookie::queue($cookie);
return Redirect::route('introduction')->withCookie($cookie);
Models/Admin:
if (Cookie::has('admin')) {
//echo 'admin is not in session but cookie';
$admin = Cookie::get('admin');
//...
but it's not go in this if never and nothing is saved in cookie !!!
Unfortunately I have upgraded to laravel 5.4 of 5.2 and anything is in the wrong way now :((((
please help me!

Laravel is encrypting cookies, so I had to add an exception for them in App\Http\Middleware\EncryptCookies\:
protected $except = [
'cookie_name'
];

Just change the way you set the cookie to Cookie::queue('admin', $admin);

Related

Laravel route group is not taken properly

I created 2 route groups in my api route file, and I can't access to routes of second group.
First group :
$api = app('Dingo\Api\Routing\Router');
$request = app('\Dingo\Api\Http\Request');
$api->dispatch($request);
/* API V1 ROUTES */
$prefix = 'test';
$api->group(['prefix' => $prefix,'version'=> 'v1'],function($api) {
$api->post('/entity/validate/{code}', [
'as' => 'validate.code',
'uses' => 'App\Http\Controllers\XXX\Api\SmsController#validateCodeV1',
]);
});
This is working perfectly and I reach my function validateCodeV1 that does perfectly its job.
On another side I have right after it
Second group :
$prefix = 'testv2';
$api->group(['prefix' => $prefix,'version'=> 'v2'],function($api) {
$api->post('/entity/validate/{code}', [
'as' => 'validate.code',
'uses' => 'App\Http\Controllers\XXX\Api\SmsController#validateCode',
]);
});
Here I have a 404 when I try to call my api with a prefix testv2/entity/validate/XXX
I don't know how I can specify properly my prefix to swap from my v1 route to my v2 route...
I use Laravel 5.5
EDIT :
check of routes contains only one of my 2 routes, even after cache clear :
php artisan route:list | grep entity/validate
| | POST | /test/entity/validate/{code} | validate.code | Closure | api.controllers |
I've tried your code and change the $api-> to Route:: and both work as they should and listed in php artisan route:list.
$prefix = 'test';
Route::group(['prefix' => $prefix,'version'=> 'v1'],function($api) {
Route::post('/entity/validate/{code}', [
'as' => 'validate.code',
'uses' => 'App\Http\Controllers\XXX\Api\SmsController#validateCodeV1',
]);
});
$prefix = 'testv2';
Route::group(['prefix' => $prefix,'version'=> 'v2'],function($api) {
Route::post('/entity/validate/{code}', [
'as' => 'validate.code',
'uses' => 'App\Http\Controllers\XXX\Api\SmsController#validateCode',
]);
});
I think, you can check your $api or $request, maybe there is an error, function, or something else that only allow v1 version.
I fixed it by mixing the 2 solutions of this post :
Dingo API - How to add version number in url?
It is not exactly a duplicate so I let my post, but if someone think it is appropriated to remove my post just ask and I will do it

Laravel Best Practice: Print Json response

I've been wondering what is the best way in Laravel to return a json array back to an ajax call. This is the way I'm working right now:
Route in web.php
Route::group(['prefix' => 'users'], function () {
Route::post('getOneTimeLink', [
'as' => 'adminUserOneTimeLink',
'uses' => 'AdminUsersController#createOneTimeLink'
]);
});
Controller in AdminUsersController.php
public function createOneTimeLink(){
$aResponse = [ 'someData' => 'someValue'];
// do some stuff here
echo json_encode($aResponse);
die()
}
but I think there is another way to return the call instead of adding the json_encode then die() the execution... but I don't know it yet. I've tried to search but haven't yet found an answer. I hope any of you can help me.
Thank you so much!
return response()->json($aResponse);
More information: https://laravel.com/docs/5.5/responses#json-responses
Please try to embed this logic into your code:
$response = array( 'status' => 'success', 'message' => $Info );
return response() ->json($response)->withHeaders($this->headerArray);

Add auth to some methods of API resource routes

I need to restrict access to the index resource so that people cant view all the submissions from a contact form.. is this possible to do via a route or what are people doing ?
Im using Laravel 5.2
Route::group(['prefix' => 'v1/api', 'middleware' => ['cors']], function(){
Route::resource('contact', 'ContactFormController', ['except' => [
'create', 'edit'
]]);
});
got it.. added this to the controller in question
function __construct() {
$this->middleware('auth', array('only' => array('index', 'show')));
}

Laravel 5.2 Auth::login($user) not working

I am writing a Laravel 5.2 application. I need to manually login the user for which I am using \Auth::login($user). I am doing it in following way.
if ($user = User::where('phone',session('phone'))->first())
{
\Auth::login($user);
// \Auth::loginUsingId($user->id);
// Auth::attempt(['email' => $user->email, 'password' => 'password']);
$data = \Auth::user(); //returning correct results
}
I have tried all the options namely Auth::login($user), Authh:loginUsingId($user->id) and attempt method. These methods are working fine as the $data variable is storing the object of correct user. But the problem is when I move to other route say '/home' the user remain no more authenticated.
What might be the wrong here? How could I do it correctly?
Since Laravel 5.2, you have to attach all your routes that need session with the 'web' middleware. See your app/Http/Kernel.php, the 'web' middleware contains the \Illuminate\Session\Middleware\StartSession.
In routes you have to use web in laravel 5.2
Route::group(['middleware' => ['web', 'auth']], function () {
Route::get('/', 'HomeController#index');
Route::get('/profile', 'HomeController#profile');
});

Laravel login redirect doesn't work

I have made the login/tregistration form. Registration works well but login redirect doesn't work. I have the following function in my controller:
public function doLogin() {
$credentials = [
'email' => Input::get('email'),
'password' => Input::get('password')
];
if (Auth::attempt($credentials)) {
return Redirect::to('/');
} else {
dd('error');
}
}
and the routes.php
Route::resource('car', 'CarController');
Route::get('users', 'UserController#index');
Route::post('users/register', array('uses' => 'UserController#store'));
Route::post('users/signin', array('uses' => 'UserController#doLogin'));
Route::get('users/logout', array('uses' => 'UserController#doLogout'));
Route::get('/', 'CarController#index');
CarController
public function index() {
$cars = DB::select('select * from cars');
$result = DB::select('select c.*, i.sgs, i.tpl, i.kasko, i.inter_permis from cars as c left join insur_docs as i on i.car_id = c.id');
$date = Carbon::now();
$limit_date = Carbon::now()->addMonths(1);
return View::make('pages.index', array(
'cars' => $cars,
'result' => $result,
'date' => $date,
'limit_date' => $limit_date,
));
}
The problem is that it doesn't redirects to index page just refresh the page. If not correct credentials it shows "error" else if correct credentials it just refresh page and doesn't redirects. I f I replace redirect with success message it shows it. I have the same code localy and login with redirect is ok, but in google app engine (my project online) doesn't redirect.
The example you have used wouldn't actually redirect the user for two reasons.
The use of Redirect::route() excepts the parameter passed to be the name of a route, eg one defined like so
Route::get('/', ['as' => 'home', 'uses' => 'YourController#yourMethod']);
To redirect here you would use Redirect::route('home').
You aren't actually returning the redirect. Any response for a route, whether it be within a controller method or a closure, must be returned using the return keyword.
So to correct your code, it'd be like this:
public function doLogin() {
$credentials = [
'email' => Input::get('email'),
'password' => Input::get('password')
];
if (Auth::attempt($credentials)) {
return Redirect::to('/');
} else {
dd('error');
}
}
I moved the credentials to an array as it looks tidier and it makes it easier to read when displaying on this site, so you don't have to do that, but it may make things easier for you.

Resources