Trying to get $user->id to filter $tasks by creator and logs gave error.
Help plz
[2019-06-28 10:52:18] local.ERROR: Trying to get property 'id' of
non-object {"exception":"[object] (ErrorException(code: 0): Trying to
get property 'id' of non-object at
/home/vitaliy/Projects/table/app/Http/Controllers/Api/GanttController.php:30)
GanttController
public function get(){
$links = new Link();
$user = Auth::user();
$task_user = TaskUser::all()->where('user_id', $user->id);
$filter_tasks = collect();
foreach ($task_user as $task){
$get_task = Task::find($task{'task_id'});
$filter_tasks[] = $get_task;
}
return response()->json([
"data" => $filter_tasks,
"links" => $links->all()
]);
}
api.php
Route::post('/login', 'Api\Auth\LoginController#login')->name('login.login');
Route::get('/tasks/self', 'Api\TaskController#self');
Route::get('/data', 'Api\GanttController#get');
Route::resource('task', 'Api\TaskController');
Route::resource('link', 'Api\LinkController');
view.blde
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
gantt.config.xml_date = "%Y-%m-%d %H:%i:%s";
gantt.init("gantt_here");
gantt.load("/api/data");
var dp = new gantt.dataProcessor("/api");
dp.init(gantt);
dp.setTransactionMode("REST");
Related
I am doing Paypal integration in Laravel. I have used composer require srmklive/paypal to install the srmklive/paypal package in this project.
When I press the PayPal button, I get this error:
Here is my code:
code from blade file:
paypal.Buttons({
createOrder: function(data, actions) {
return fetch('api/paypal/order/create/', {
method: 'post',
body:JSON.stringify({
"value":100
})
}).then(function(res) {
return res.json();
}).then(function(orderData) {
return orderData.id;
});
},
onApprove: function(data, actions) {
return fetch('/api/paypal/order/capture/', {
method: 'post',
body: JSON.stringify({
orderID: data.orderID
})
}).then(function(res) {
return res.json();
}).then(function(orderData) {
var errorDetail = Array.isArray(orderData.details) && orderData.details[0];
if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
return actions.restart();
}
if (errorDetail) {
var msg = 'Sorry, your transaction could not be processed.';
return alert(msg); // Show a failure message (try to avoid alerts in production environments)
}
});
}
}).render('#paypal-button-container');
code from paymentController:
class PaymentController extends Controller
{
public function create(Request $request){
$data = json_decode($request->getContent(), true);
$provider = \PayPal::setProvider();
$provider->setApiCredentials(config('paypal'));
$token = $provider->getAccessToken();
$provider->setAccessToken($token);
$price = Plan::getSubscriptionPrice($data['value']);
$description = Plan::getSubscriptionDescription($data['value']);
$order = $provider->createOrder([
"intent" => "CAPTURE",
"purchase_units" => [
[
"amount" => [
"currency_code" => "USD",
"value" => $price
],
"description" => $description
]
]
]);
return response()->json($order);
}
public function capture(Request $request) {
$data = json_decode($request->getContent(), true);
$orderId = $data['orderID'];
$provider = \PayPal::setProvider();
$provider->setApiCredentials(config('paypal'));
$token = $provider->getAccessToken();
$provider->setAccessToken($token);
$result = $provider->capturePaymentOrder($orderId);
return response()->json($result);
}
}
How can I solve this error?
The route api/paypal/order/create/ is returning/outputting text that is not JSON, such as an HTML error page or something else that begins with an HTML tag.
The route must only output JSON, and must contain a valid id from the PayPal API.
Every time I run the test, I'm getting a 403 response status, what am I doing wrong in here?
I have tried to remove Passport authorization from the test, but then I'm getting a redirect to a login page, 302 status response.
//PostTest:
public function test_can_update_post()
{
//creating a user
$user = factory(User::class)->create();
//creating an author for post
$author = factory(Author::class)->create([
'user_id' => $user->id,
]);
//creating a post
$post = factory(Post::class)->create([
'author_id' => $author->id,
]);
$data = [
'title' => $this->faker->title,
'content' => $this->faker->paragraph,
];
//authorizing user
//I have tried to remove this line, then I'm gettig a redirect to login page 302
$user = Passport::actingAs($user);
$this->actingAs($user)
->patch(route('posts.update', $post->id), $data)
->assertStatus(200);// why I'm getting 403???
}
//API route:
Route::patch('posts/{post}')
->uses('PostController#update')
->middleware('auth:api')
->name('posts.update');
//PostController update method:
public function update(PostUpdateRequest $request, Post $post)
{
$this->authorize('update', $post);
$post->title = $request->input('title');
$post->content = $request->input('content');
$post->save();
return new PostResource($post);
}
//PostPolocy
public function update(User $user, Post $post)
{
return Author::where('user_id', $user->id)->first()->id === $post->author_id;
}
I expect response status 200
I have changed the line in PostPolicy update method to:
if(!$user->author) {
return false;
}
return $user->author->id == $post->author_id;
This worked for me.
I have a Vue.js form and I submit the form using Axios. I'm able to save the data to my database. However, when I want to save my dynamically added input fields I get this error message...
Invalid argument supplied for foreach
The problem is that it's not an array but it should be. As you can see, I would like to send the teams[] array from the Vue component to the Laravel backend with Axios. When i console.log() teams [object object], [object object].
app.js
new Vue({
el: '#regapp',
data: {
username: '',
email: '',
password: '',
password_confirmation: '',
teams: [
{
name: '',
role: '',
linkedin: '',
profileimg: ''
}
],
methods: {
onSubmit() {
axios.defaults.headers.common["X-CSRF-TOKEN"] = document
.querySelector('meta[name="csrf-token"]')
.getAttribute("content");
let formData = new FormData();
formData.append('username', this.username);
formData.append('email', this.email);
formData.append('password', this.password);
formData.append('password_confirmation', this.password_confirmation);
formData.append('teams', this.teams);
axios.post('register', formData)
.then(response => alert('Success'))
.catch(error => this.errors.record(error.response.data.errors));
}
}
}
});
Controller.php
protected function create(array $data)
{
$user = new User();
$user->name = $data['username'];
$user->email = $data['email'];
$user->password = Hash::make($data['password']);
$user->save();
// Here I try to loop trough teams and save each of them names into db.
if ($data['teams'][0] != NULL) {
$format = (array)$data;
foreach ($format['teams'] as $teams) { // The error is here
$team = new Team();
$team->user_id = $user->id;
$team->tmembername = $teams->name;
$team->save();
}
}
return $user;
}
Thanks Hassan for the help.
The problem was that this.teams is an array of objects - it just tries to convert the Object to a String, hence getting [object Object].
So i can't do this:
formData.append('teams', this.teams);
I had to:
var teammemb = JSON.stringify(this.teams);
Then:
formData.append('teams', teammemb);
On my RegisterController.php
$csapat = (json_decode($data['teams']));
if (is_array($csapat) || is_object($csapat)) {
// in this contition, foreach gonna work only array or object exist
foreach ($csapat as $teams) {
$team = new Team();
$team->ico_id = $ico->id;
$team->tmembername = $teams->name;
$team->save();
}
}
It works now.
I am developping an application and I got a problem in my front-end part. It's related to Symfony and Ajax. So I am using a session variable in order to add a student to a school before sending the form of school to the server (back-end). I am using then some Ajax. I do not how to debug it. I tried what it is posted in the net but it does not work. I was able to add a student to a school but I was not able to update the student information. That's seem easy but it's not as I thought. Here is an ajax call that I am using in my SchoolCreate.html.twig:
function ajax () {
$.ajax({
type: 'POST',
url: "{{ path('student_add') }}",
data: $('#addStudent').serialize(),
success: function (response) {
var htmlToDisplay = response.trim();
$('#students').html(htmlToDisplay);
}
});
}
My modal used to create school:
<div class="modal-body">
{{ render(controller('AppBundle:School:addStudent')) }}
</div>
addStudent:
public function addStudentAction(Request $request) {
$student = new Student();
$form = $this->createForm(StudentType::class, $student);
$form->handleRequest($request);
$headers = array('Accept' => 'application/json');
$encoders = array(new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$serializer = new Serializer($normalizers, $encoders);
if ($request->isXmlHttpRequest())
{
$session = $request->getSession();
$student = $form->getData();
if ($session->has('students'))
$students = $session->get('students');
$students[] = $student;
$session->set('$students', $students);
$template = $this->renderView('AppBundle:School:StudentList.html.twig', array(
'students' => $students
));
return new Response($template);
}
return $this->render('AppBundle:Student:StudentAdd.html.twig', array(
'form' => $form->createView()
));
}
I try to do the same in updateStudent function but I got a problem related to 30 second exceeded and I do not know how to debug in Ajax. I define my bottom of update inside StudentList.html.twig
Thanks,
EDIT : I am testing it now, so weird that sometimes it works and sometimes it gives me that error.
I have an application, I've override the logout function in Laravel so I have this in my AuthController.php
public function getLogout()
{
$userid = Auth::user()->id;
date_default_timezone_set('Asia/Taipei');
$today = date('Y-m-d');
$logHour = new LoginHour();
$checkLogin = $logHour->checkLoginHoursOut(intval($userid), $today);
if($checkLogin != null)
{
$loginhours = '';
$timestamp = date('Y-m-d h:i:s');
$timestamp2 = strtotime($timestamp);
$userLastLogin = $checkLogin[0]->timestamp;
$userLastLogin2 = strtotime($userLastLogin);
// Get difference in hours
$diffHours = round(($timestamp2 - $userLastLogin2) / 3600, 2);
LoginHour::where('date', '=', $today)->
where('user_id', '=', $userid)->
update(['loginhours' => $checkLogin[0]->loginhours + $diffHours, 'status' => 0, 'timestamp' => $timestamp]);
}
Auth::logout();
return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/auth/login');
}
But for some reason when I am trying to logout I have this error:
Trying to get property of non-object
Which points me to this line
$userid = Auth::user()->id;
What could be the problem? I believe I could still access the Auth coz I'm not yet calling the Auth::logout(); before that line?
I guess that the problem exists when you visit the logout route, without a logged in user.
So, you should check it at the top.
public function getLogout()
{
if (Auth::guest()) return;
...
}