Laravel Best Practice: Print Json response - laravel

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);

Related

Missing required parameters for [Route: reviews.show] (from controller)

i want to route a new page from controller, i am getting data successfully when passing in route but getting error.
here is my particular part of controller -
$use = User::find($user->id);
$pos = posts::find($post->id);
//dd($user1, $post1);
return redirect()->route('reviews.show', $pos, $use);
in web.php part -
Route::get('p/{posts}/review/{user}','ReviewController#show')->name('reviews.show');
in show method -
public function show($posts, $user)
{
return view('posts.reviews.reviewshow', ['posts' => $posts], ['user' => $user]);
}
You have to use like this
return redirect()->route('reviews.show', ['posts' => $pos, 'user' => $use]);
route() calls in general take URL parameters as associative array. You are using helper function for it, but it still applies.
redirect()->route('reviews.show', ['posts' => $pos, 'user' => $use]);
When you pass 2 paramters to a route you send them as Array
return redirect()->route('reviews.show', [ $pos, $use ]);
This is your issue

Cookie::get returns null, laravel 5.4

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);

Getting NotFoundHttpException for my edit route

This is my route
Route::get(
'account-executive/{$id}/edit',
array(
'as' => 'vendor-edit',
'uses' => 'AdminController#updateVendor'
)
);
This is my method
public function updateVendor($id)
{
$vendor = Vendor::findOrFail($id);
return View::make('admin.edit-account-executive');
}
I keep getting NotFoundHttpException. Any ideas as to why?
Your route definition isn't correct.
Route::get('account-executive/{$id}/edit', array('as' => 'vendor-edit','uses' => 'AdminController#updateVendor'));
You don't need a $ sign in definition of route parameter. So you should just write account-executive/{id}/edit.
Try it.

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.

Laravel 4 : Route returning wrong information

I am setting up an API with Laravel so that I can connect with an AngularJS front-end.
I have 2 routes that go to the same controller method -> BallController#getSpecs
My routes are set up as follows:
Route::group(['prefix' => '/api/v1', 'before' => 'auth.basic'], function() {
Route::group(['prefix' => '/ball'], function() {
Route::get('/', 'BallController#getIndex');
Route::get('{id}', 'BallController#getIndex');
Route::get('specs', 'BallController#getSpecs');
Route::get('{id}/specs', 'BallController#getSpecs');
});
});
Now I am having trouble with Route::get('specs', 'BallController#getSpecs'); route.
The getSpecs method is defined as follows:
public function getSpecs($id = null)
{
if(empty($id))
{
Ball::all()->each(function($ball) {
$json = [$ball->id => [
'name' => $ball->name,
'core' => $ball->core->toArray(),
'coverstock' => $ball->coverstock->toArray(),
'finish' => $ball->finish->toArray(),
'manufacturer' => $ball->manufacturer->toArray()
]];
});
return Response::json($json);
}
else
{
$ball = Ball::find($id);
if(empty($ball))
{
return Response::json('You\'ve got no ballss', 404);
}
else
{
return Response::json([$ball->id => [
'name' => $ball->name,
'core' => $ball->core->toArray(),
'coverstock' => $ball->coverstock->toArray(),
'finish' => $ball->finish->toArray(),
'manufacturer' => $ball->manufacturer->toArray()
]]);
}
}
}
When I call /api/v1/ball/1/specs specifying an id I get the correct information back, however when I call /api/v1/ball/specs my function returns my error message 'You've got no balls'
ID should be null in this cast putting me into the first part of my if statement but for some reason I am getting into my else and getting my error because obviously no ID was provided and the ball won't exist.
Any help/insight will be appreciated.
Edit: I think it may be sending it to the wrong method. I think that /api/v1/ball/specs is being sent to BallController#getIndex instead of BallController#getSpecs.
The problem is in this part of the routing:
Route::get('{id}', 'BallController#getIndex');
Route::get('specs', 'BallController#getSpecs');
When it sees "/api/v1/ball/specs", it will actually call getIndex() with the "id" parameter set to "specs", because that's the first matching route. One way to fix it would be to define the "specs" route first before you define the "{id}" route. But a better solution would be to limit the accepted values of the "{id}" parmeter like this...
Route::get('{id}', 'BallController#getIndex')->where('id', '[0-9]+');
One other suggestion, there shouldn't be a leading "/" in your prefix values (apparently the code may be working anyway, but they aren't really supposed to be there. So the complete updated route might look like this...
Route::group(['prefix' => 'api/v1', 'before' => 'auth.basic'], function() {
Route::group(['prefix' => 'ball'], function() {
Route::get('/', 'BallController#getIndex');
Route::get('specs', 'BallController#getSpecs');
Route::get('{id}', 'BallController#getIndex')->where('id', '[0-9]+');
Route::get('{id}/specs', 'BallController#getSpecs')->where('id', '[0-9]+');
});
});

Resources