I have a contact form. There is some code from the confirm page and the final page with the 'your message has been sent' message controller code.
I need to add a couple of post data to the 'confirm' page.
How do I recieve those post data and add them to the $data array at the complete function?
/*
* confirm page
*/
public function confirm(Request $request)
{
$rules = [];
$this->validate($request, $rules);
$data = $request->all();
$request->session()->put('data',$data);
dd($request);
return view('mail.confirm', compact("data"));
}
/*
* final page (your message has been sent page)
*/
public function complete(Request $request)
{
$data = $request->session()->pull('data');
$token = array_shift($data);
$Contact = Contact::create($data);
$data = session()->regenerateToken();
return view('mail.complete');
}
To add post data, you can retrieve from the $request variable using:
$request->all();
For your case:
public function complete(Request $request)
{
$data = $request->session()->pull('data');
$token = array_shift($data);
$data = array_merge($data, $request->all());
$Contact = Contact::create($data);
$data = session()->regenerateToken();
return view('mail.complete');
}
Related
I have an app built on laravel 8 with a Vue Spa front end, using Sanctum.
I have a controller method that requests from another Laravel project (using its Sanctum API) so essentially, the Spa requests from Laravel 1, which requests from Laravel 2 project.
Following the responses from L2 project back, the Controller method on L2 is:
public function popular(Request $request)
{
$limit = 20;
if ($request->has('limit')) {
$limit = $request->limit;
}
$perPage = 20;
if ($request->has('per_page')) {
$limit = $request->per_page;
}
if ($request->has('page')) {
$articles = $request
->user()
->articles()
->activeArticles()
->select('articles.uuid', 'articles.title')
->orderBy('articles.views', 'DESC')
->simplePaginate($perPage);
} else {
$articles = $request
->user()
->articles()
->activeArticles()
->select('articles.uuid', 'articles.title')
->orderBy('articles.views', 'DESC')
->limit($limit)
->get();
}
return $articles;
}
This response is received by L1 Controller method, and sent back to the Spa like this:
public function popular(Request $request)
{
$apiEndPoint = self::$apiBaseUrl . '/article/popular';
$response = self::$httpRequest->get($apiEndPoint, $request->query());
if (!$response->successful()) {
return $this->setMessage(trans('help.api_error'))->send();
}
$body = $response->getBody();
return response(['data' => $body]);
}
With this return:
return response(['data' => $body]);
I get and empty data object:
{
data: {}
}
And with this return:
return response($body);
I get the payload as text / string:
[{"id":15,"uuid":"c6082143-0f34-443b-9447-3fa57ed73f48","name":"dashboard","icon":"database","active":1,"owned_by":2,"product_id":4,"created_at":"2021-12-23T11:46:35.000000Z","updated_at":"2021-12-23T11:46:35.000000Z"},{"id":16,
How do I return the $body as JSON to the Spa?
UPDATE: I tried suggestions below, but the result is still exception.
return response()->json($body);
Returns:
"message": "json_decode(): Argument #1 ($json) must be of type string, GuzzleHttp\\Psr7\\Stream given",
So getting the body in getBody() returns a string I understood.
If I Log the $body I get:
$body = $response->getBody();
Log::info($body);
[2021-12-25 23:15:36] local.INFO: {"current_page":2,"data":[{"uuid":"aa4a47bf-4975-4e78-868a-103398934504","title":"Ritchie-Hoeger"},
Thanks for any help and happy festive season.
API Responser
First create a trait in laravel in 'app\Traits\ApiResponser.php'
<?php
namespace App\Traits;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
trait ApiResponser{
public function set_response($data, $status_code, $status, $details)
{
$resData = response(json_encode(
[
'status' => $status, // true or false
'code' => $status_code,
'data' => $data,
'message' => $details
]
), 200)
->header('Content-Type', 'application/json');
$data = [];
return $resData;
}
}
Second in any controller call this trait's function set_response()
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Traits\ApiResponser;
use Illuminate\Http\Request;
class ListController extends Controller
{
use ApiResponser;
public function getAllUserList(Request $request)
{
$data = User::select('id', 'name', 'email')->get();
return $this->set_response(['data' => $data], 200,'success', ['User list']);
}
}
Output will be like this
use the json helper function
return response()->json($body);
or
use Response;
return Response::json($body);
This will create an instance of \Illuminate\Routing\ResponseFactory. See the phpDocs for possible parameters below:
/**
* Return a new JSON response from the application.
*
* #param string|array $data
* #param int $status
* #param array $headers
* #param int $options
* #return \Symfony\Component\HttpFoundation\Response
* #static
*/
public static function json($data = array(), $status = 200, $headers = array(), $options = 0){
return \Illuminate\Routing\ResponseFactory::json($data, $status, $headers, $options);
}
I needed to ->getContents() after the ->getBody()
$body = $response->getBody()->getContents();
All good again...
I want the blocked user can not perform a password reset link, receive an error message and be forwarded to a page. If a user is blocked, a 2 is stored in the table user, active. How can I do that?
I found thiy code from laravel:
/**
* Send a reset link to the given user.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
public function sendResetLinkEmail(Request $request)
{
$this->validateEmail($request);
// We will send the password reset link to this user. Once we have attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$response = $this->broker()->sendResetLink(
$request->only('email')
);
return $response == Password::RESET_LINK_SENT
? $this->sendResetLinkResponse($response)
: $this->sendResetLinkFailedResponse($request, $response);
}
No need to overwrite sendResetLinkEmail function, you can just overwrite the validateEmail like this
protected function validateEmail(Request $request)
{
$this->validate($request,
['email' => ['required','email',
Rule::exists('users')->where(function ($query) {
$query->where('active', 1);
})
]
]
);
}
OR
if you want to redirect to custom url then overwrite sendResetLinkEmail function with manual validation like this
public function sendResetLinkEmail(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => ['required', 'email',
Rule::exists('users')->where(function ($query) {
$query->where('active', 1);
})
]
]);
if ($validator->fails()) {
return redirect('some_other_url')
->with('fail', 'You can not request reset password, account is block');
}
// We will send the password reset link to this user. Once we have attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$response = $this->broker()->sendResetLink(
$request->only('email')
);
return $response == Password::RESET_LINK_SENT
? $this->sendResetLinkResponse($response)
: $this->sendResetLinkFailedResponse($request, $response);
}
I am having a problem returning a proper response to an ajax request I made.
Basically, I have a checkbox which when changed() fires an ajax with csrf-token to be accepted in POST method, the changes reflected on the database is successful but the error starts on returning the "status" of the process to the ajax.
Heres my controller method:
public function update(Request $request, $id)
{
$result = ItemPrice::toggleRestockable($id);
return $result;
}
$result is the output of DB::update() method
The ajax goes to error: block with Internal Server Error 500 regardless whether the query was a success or not.
The responseText of data variable in ajax was mainly:
(1/1) UnexpectedValueException
The Response content must be a string or object implementing __toString(), "boolean" given.
Now I know I am returning boolean or technically an integer because it was a result of DB::update() which returns the number of rows affected by the update.
Now how could I properly return a response that an ajax can understand?
Try This
public function update(Request $request, $id)
{
$result = ItemPrice::toggleRestockable($id);
return Response::json(['success' => $result], 200);
}
Create one base ApiController abstract class and extend it in your any controller. so you no need to prepare response obj for success and error in every function and every controller. you just call function. example given here.
// Base ApiController
abstract class ApiController extends Controller
{
/**
* Make standard response with some data
*
* #param object|array $data Data to be send as JSON
* #param int $code optional HTTP response code, default to 200
* #return \Illuminate\Http\JsonResponse
*/
protected function respondWithData($data, $code = 200)
{
return Response::json([
'success' => true,
'data' => $data
], $code);
}
/**
* Make standard successful response ['success' => true, 'message' => $message]
*
* #param string $message Success message
* #param int $code HTTP response code, default to 200
* #return \Illuminate\Http\JsonResponse
*/
protected function respondSuccess($message = 'Done!', $code = 200)
{
return Response::json([
'success' => true,
'message' => $message
], $code);
}
/**
* Make standard response with error ['success' => false, 'message' => $message]
*
* #param string $message Error message
* #param int $code HTTP response code, default to 500
* #return \Illuminate\Http\JsonResponse
*/
protected function respondWithError($message = 'Server error', $code = 500)
{
return Response::json([
'success' => false,
'message' => $message
], $code);
}
How to use functions of base class. see example here
public function update(Request $request, $id)
{
try{
$result = ItemPrice::toggleRestockable($id);
return $this->respondWithData($result);
}catch(Exception $e){
return $this->respondWithError($e->getMessage());
}
}
how to extend base controller into your controller
class TestController extends ApiController {}
JsonResponse is the class you need.
return response()->json($result);
using helpers. Use ->toArray() on $result if dealing with collections.
return $result;
will return the object of data, there are multiple ways to handle this depending on the return type of your toggle function.
The Typical way to handle an AJAX request is to save data and return the status and message.
in your scenario, I could use a response to JSON
public function update(Request $request, $id)
{
$status = 500;
$message = 'An Un expected error Occured';
try {
$result = ItemPrice::toggleRestockable($id);
//assuming toggleRestockable function will return bool
if ($result) {
$status = 200;
$message = 'Successfully Updated';
}
return response()->json(['status' => $status, 'message' => $message]);
} catch (Exception $e) {
return response()->json(['status' => 500, 'message' => $e->getMessage()]);
}
}
This way of doing works fine for me
public function update(Request $request, $id)
{
$this->validate($request, [
//some of your data =>'required|min:4'; <-your rules
]);
$result = ItemPrice::findOrFail($id);
//something request;
$result->save();
return response()->json(['result'=>$result]);
}
and you can call your error by using this
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
i hope it will helps you a lot :)
I'm making a site with laravel that has a CRUD functie for Users and posts. That part is completed.
After that I made a register function, that also worked.
But when I tried to make a Login page some is wrong.
As soon as I select the, "login"-button a error page shows up with the error:
Class 'Auth' not found
My UserController:
<?php
class UserController extends BaseController {
protected $layout = "layouts.main";
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
// get all the users
$users = User::all();
// load the view and pass the users
return View::make('users.index') ->with('users', $users);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
// load the create form (app/views/users/create.blade.php)
return View::make('users.create');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
$rules = array(
'email' => 'required|email|unique:users',
'password' => 'required|min:8'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if($validator->fails()) {
return Redirect::to('users/create')
->withErrors($validator)
->withInput(Input::except('password'));
}else{
//store
$user = new User;
$user->email = Input::get('email');
$user->password = Input::get('password');
$user->save();
// redirect
Session::flash('message', 'Successfully created User!');
return Redirect::to('users');
}
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
// get the User
$user = User::find($id);
// show the view and pass the user to it
return View::make('users.show') ->with('user', $user);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
// get the user
$user = User::find($id);
// show the edit form and pass the User
return View::make('users.edit') -> with('user', $user);
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
$rules = array(
'email' => 'required|email',
'password' => 'required|min:8'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if($validator->fails()) {
return Redirect::to('users/' . $id . '/edit')
->withErrors($validator)
->withInput(Input::except('password'));
}else{
//store
$user = User::find($id);
$user->email = Input::get('email');
$user->password = Input::get('password');
$user->save();
// redirect
Session::flash('message', 'Successfully updated User!');
return Redirect::to('users');
}
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
// delete
$user = User::find($id);
$user->delete();
// redirect
Session::flash('message', 'Successfully deleted the User!');
return Redirect::to('users');
}
//dit is toegevoegd
public function getRegister() {
$this->layout = View::make('login.register');
}
public function postCreate() {
$validator = Validator::make(Input::all(), User::$rules);
if ($validator->passes()) {
// validation has passed, save user in DB
$user = new User;
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->save();
return Redirect::to('login/login')->with('message', 'Thanks for registering!');
} else {
// validation has failed, display error messages
return Redirect::to('login/register')->with('message', 'The following errors occurred')->withErrors($validator)->withInput();
}
}
public function __construct() {
$this->beforeFilter('csrf', array('on'=>'post'));
$this->beforeFilter('auth', array('only'=>array('getDashboard')));
}
public function getLogin() {
$this->layout = View::make('login.login');
}
public function postSignin() {
$user = array('email'=>Input::get('email'), 'password'=>Input::get('password'));
if (Auth::attempt($user)) {
return Redirect::to('login/dashboard')->with('message', 'You are now logged in!');
} else {
return Redirect::to('login/login')
->with('message', 'Your username/password combination was incorrect')
->withInput();
}
}
public function getDashboard() {
$this->layout = View::make('login.dashboard');
}
}
My Login.blade.php:
#include('header')
<h1>Login page</h1>
{{ Form::open(array('url'=>'login/signin', 'class'=>'form-signin')) }}
<h2 class="form-signin-heading">Please Login</h2>
{{ Form::text('email', null, array('class'=>'input-block-level', 'placeholder'=>'Email Address')) }}
{{ Form::password('password', array('class'=>'input-block-level', 'placeholder'=>'Password')) }}
<br><br>
{{ Form::submit('Login', array('class'=>'btn btn-large btn-primary btn- block'))}}
{{ Form::close() }}
#include('footer')
And my routes:
<?php
Route::get('home', function()
{
return View::make('home');
});
Route::get('/', function()
{
return View::make('home');
});
Route::resource('users', 'UserController');
Route::resource('posts', 'PostController');
Route::controller('login', 'UserController');
Anybody who can help me?
You need to add use Auth;
or use \Auth::
To use the Auth facade, you have to import it into your namespace.
A better option is to use the helper function instead:
if (auth()->attempt($user)) {
//
}
isset(auth()->user()->id)
to check is user logged in or not.
I don't know how to redirect errors to a form if it's not valid with Symfony2?
So I use the Assert in my entity like that:
/**
* #ORM\Column(type="string", length=255, nullable=false)
* #Assert\NotBlank()
*/
private $title;
And this is my createAction method :
public function createAction(Request $request)
{
$task = new Task();
$form = $this->createForm(new TaskType(), $task);
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($task);
$em->flush();
}
// What should I do here if the form is not valid
$this->get('session')->getFlashBag()->add('success', 'The task has been added successfully!');
return $this->redirect($this->generateUrl('crm_tasks'));
}
return $this->render('LanCrmBundle:Task:create.html.twig', array(
'form' => $form->createView(),
));
}
What should I do to return errors to the form?
You should include the FlashBag() and return statement inside the if($form->isValid) condition.
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($task);
$em->flush();
$this->get('session')->getFlashBag()->add('success', 'The task has been added successfully!');
return $this->redirect($this->generateUrl('crm_tasks'));
}
If not valid, the user will be redirected to the form, displaying the error if Symfony catched it.