I am new to Laravel and I need to debug some variables (requests) in my Controller. I've read that you can output variables into a view with functions like dd(). My frontend is built with Vuejs and it seems to be a hassle to echo them out from the Controller to the frontend. Are there better ways than echoing them out? Is it possible to log them?
NewsletterController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class NewsletterController extends Controller
{
public function submit(Request $request) {
$this->validate($request, [
'email' => 'required | email'
]);
$data = array('email' => $request);
dd($data);
DB::table('newsletter')->insert($data);
return response()->json(null, 200);
}
}
What would be the best way to debug $data variable in this case?
You can use var_dump
var_dump($data);
https://www.php.net/manual/en/function.var-dump.php
I came accross this:
\Log::info(print_r($var, true));
which dumps a variable or any content into laravel.log in a somehow human readable format.
dd is fine. You can inspect the output in the console.
Or you can dump the variable as json with
echo json_encode($data);
die;
Related
I have created a laravel application to store employee data, but when I submit the form it gives me the following error, what should I do to avoid this problem. thanks
This is my EmployeeController store method
public function store(Request $request)
{
$this->validate($request,array(
'lastname'=>'required|max:60',
'firstname'=>'required|max:60',
'middlename'=>'required|max:60',
'address'=>'required|max:120',
'NIC'=>'required|max:10',
'city_id'=>'required|max:60',
'state_id'=>'required|max:60',
'mobile'=>'required|max:10',
'email'=>'required|max:60',
'postal_code'=>'required|max:10',
'birthdate'=>'required|date',
'date_hired'=>'required|date',
'department_id'=>'required|max:10',
));
$employee = new Employee();
$employee->lastname=$request->lastname;
$employee->firstname=$request->firstname;
$employee->middlename=$request->middlename;
$employee->address=$request->address;
$employee->NIC=$request->NIC;
$employee->city_id=$request->city_id;
$employee->state_id=$request->state_id;
$employee->mobile=$request->mobile;
$employee->email->$request->email;
$employee->postal_code=$request->postal_code;
$employee->birthdate=$request->birthdate;
$employee->date_hired=$request->date_hired;
$employee->department_id=$request->department_id;
$employee->save();
}
Form header
{!! Form::open(['route'=>'employee.store','class'=>'form-horizontal p-t-20']) !!}
Classes i used for the controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Department;
use Illuminate\Support\Facades\DB;
use App\Employee;
There is an error in your code.
$employee->email->$request->email;
This should be,
$employee->email = $request->email;
By the looks of it you are trying to validate the $request variable itself. Hence the Trying to get property POST
Should it not be...
$request->validate(array(
'lastname'=>'required|max:60',
'firstname'=>'required|max:60',
'middlename'=>'required|max:60',
'address'=>'required|max:120',
'NIC'=>'required|max:10',
'city_id'=>'required|max:60',
'state_id'=>'required|max:60',
'mobile'=>'required|max:10',
'email'=>'required|max:60',
'postal_code'=>'required|max:10',
'birthdate'=>'required|date',
'date_hired'=>'required|date',
'department_id'=>'required|max:10',
));
ErrorException: Trying to get property 'POST /Addpatients HTTP/1.1
This ERROR IS DUE to
when you difine your variable in any method Please check that you doest not define as below because it gives the error
$patients->address->$request->input('address');
The solution is of this is as below
$patients->address=$request->input('address');
I am getting 404 while am trying to access my api url here is my route :
MY Api route list:
<?php
use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/', function (Request $request) {
return $request->user();
});
Route::get('testapi','ApiDoctorController#testapi');
and the controller function that is provide data response is :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ApiDoctorController extends Controller
{
public function testapi(){
$data = [
'name' => 'HEllo',
'age' => '24',
'height' => '5.4'
]
return response()->json($data);
}
}
When i try to access it in post-man at http://mydomain/project/api/testapi
its showing 404 error i am new to laravel help me out please
[![POSTMAN RESPONSE][1]][1][1]: https://i.stack.imgur.com/1uV6Z.png
First of all your missing the semicolon on the end of your data array.
Is Route::get('testapi','ApiDoctorController#testapi'); in your routes/api.php?
If not you'll need to define it so.
In postman you're doing domain/project/api/testapi when it should be domain/api/testapi as that is what you have specified in your routes file unless your entire laravel install is in domain/project.
I have added the semi-colon for you and formatted the code. If you're testing via postman please ensure that CSRF is disabled in your App/Http/Kernel.php (Just comment it out for your testing) then place it back in when you've setup authentication.
Let me know if this helps!
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ApiDoctorController extends Controller
{
public function testapi()
{
$data = [
'name' => 'Hello',
'age' => '24',
'height' => '5.4'
];
return response()->json($data);
}
}
Thanks everyone i got it i just add public after my project directory and it work thanks to all of you for your valuable time
So far all attempts to modify the routing methods have failed.
Been following some documentation on laravel restful controllers and have one set up to do basic editing and adding of items to a database. It was going well till I hit the snag on... well I'm not sure what precisely is triggering the problem, but basically, everything works till I hit submit on the form and then it's Game Over.
Normally I'd be able to diagnose this by checking to see if I'm using the right call, or made a spelling mistake or something. But this is a new request for me, so I can't quite debug where the problem is coming from.
This is the error those who know what to look for. In full here.
MethodNotAllowedHttpException in RouteCollection.php line 218:
My routes are pasted here.
A printout of the routes is here:
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\ContactFormRequest;
use App\UserEdit;
use DB;
use App\Http\Requests;
class EditUserController extends Controller
{
public function index()
{
$array = UserEdit::all()->toArray();
return view('UserEntry', compact('array'));
}
public function create()
{
$id = UserEdit::find(715)->toArray();
return view('NewUser', compact('id'));
}
public function store(UserFormRequest $request)
{
//$user = new UserEdit([
// 'name'=>$request->get('First_Name'),
// 'email'=>$request->get('email'),
// 'username'=>$request->get('name')
//]);
//
//$user->save();
//return \Redirect::route('users')->with('message', 'Nice Work.');
}
public function show($id)
{
try {
$array = UserEdit::findorFail($id)->toArray();
return view('UserEdit')->with('array', $array);
} catch(\Exception $e) {
return \Redirect::route('users.index')
->withMessage('This user does not exist');
}
}
public function edit($id)
{
$user = UserEdit::findorFail($id);
return view('EditUser')->with('user',$user);
}
public function update($id, UserFormRequest $request)
{
$user = UserEdit::findorFail($id);
$user->update([
'name' => $request->get('name'),
'email' => $request->get('email')
]);
return \Redirect::route('users.edit', [$user->id])->with('message', 'Details Updated!');
}
public function destroy($id)
{
//
}
}
The Blade is here.
if you have a hard time finding the solution the easiest solution is using
Route::any('users/{user}', 'UserEntryController#update');
this allow you to access this action with any method type
OR
Route::match(array('get', 'put'), 'users/{user}', 'UserEntryController#update');
so you need 2 method which are
get -> view
put -> submit update
you can just indicate which method type you want to be accessible with in this action
i think you are using model in form.try this
{{ Form::open(['method' => 'put', 'route'=>['users.update', $user->id], 'class'=>'form']) }}
As per your route list and route put doesnt taking id so you get method not found exception
PUT users/{user} App\Http\Controllers\EditUserController#update
instead of using resouce just type each route for each method
Route::put('users/{user}', 'EditUserController #update');
It seems like after sorting out the routes, the issue fell to a bad capitalisation. $user->id should have been $user->ID.
I'm new to coding and Laravel 5.1, and after watching the tutorials by Laracasts I have been creating my own webpage. I came across and error that I cant fix...
Method [send] does not exist.
My code looks like this:
namespace App\Http\Controllers;
use Mail;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class ContactController extends Controller
{
/**
*
* #param Request $request
*/
public function emailContactForm (Request $request){
$msg = $request->input('message');
$name = $request->input('name');
$email = $request->input('email');
//
$this->validate($request, [
'title' => 'required|max 500',
'name' => 'required',
'email' => 'required',
]);
//
Mail::send(
'emails.contactForm',
[
'message'=>$msg,
'name'=>$name,
],
function($m) use ($email) {
$m->to('jessica.blake#autumndev.co.uk', 'say hi')
->subject('new message')
->from($email);
}
);
//
return;
}
}
I'm trying to use the mail function, which we have now got working, but the send still doesn't? Any suggestions? Thanks!
EDIT: Full stack trace as per laravel log file: http://pastebin.com/ZLiQ7Wgu
At the very first sight, you are calling the controller method send() but you actually named it emailContactForm()
You dont post routes and actions so the quick fix by now is trying to rename emailContactForm to send, despite instead you should probably need to review all your related routing logic.
I have a symfony website, and Im trying to do some unit testing. I have this kind of test where I try to submit something:
<?php
namespace Acme\AcmeBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class HomeControllerTest extends WebTestCase {
public function testrandomeThings() {
$client = static::createClient();
$crawler = $client->request(
'POST',
'/',
array(
"shopNumber" => 0099,
"cardNumber" => 231,
"cardPIN" => "adasd"),
array(),
array());
}
but I dont think that the data Im sending is being received in the controler:
class HomeController extends Controller
{
public function indexAction()
{
var_dump($_POST);
die;
return $this->render('AcmeBundle:Home:index.html.twig');
}
}
the var_dump is actually returning me an empty array.
What am I missing to send information through my POST request?
$_POST is a variable filled by PHP and the symfony request is only created from this globals if called directly over http. The symfony crawler doesn't make a real request, it creates a request from the parameters supplied in your $client->request and executes it. You need to access this stuff via the Request object. Never use $_POST, $_GET, etc. directly.
use Symfony\Component\HttpFoundation\Request;
class HomeController extends CoralBaseController
{
public function indexAction(Request $request)
{
var_dump($request->request->all());
die;
return $this->render('CoralWalletBundle:Home:index.html.twig');
}
}
use $request->request->all() to get all POST parameters in an array. To get only a specific parameter you can use $request->request->get('my_param'). If you ever need to acces GET parameters you can use $request->query->get('my_param'), but better set query parameters already in the routing pattern.
I think you're trying to do this:
$client = static::createClient();
$client->request($method, $url, [], [], [], json_encode($content));
$this->assertEquals(
200,
$client->getResponse()
->getStatusCode()
);
You're putting your data (content) in as the params array but you want to put it in as the raw body content which is a JSON encoded string.