How to get all users from laravel api?

I ma building an admin dashboard for my app with angular as frontend framework and Laravel API as a backend.

I want to manage all registered users from the user’s table. I am using a passport for user authentication and giving token to each user.

What I know is, without the token, I cannot access the individual user. But i need access to all users ,perform [edit,delete] .

Without middleware i can get all registered user [but this is not a secure way in my opinion] Route::get('/users','AuthRegisterController@index')->middleware('auth');

can I get access to all users ? or there are other methods to achieve this?
I need suggestion. what is the appropriate method to get all users [which in normal way can only be accessed when the user is logged in and gives single user information]?


Source: stackoverflow-php

Laravel Router Draws in URL Encoding from View, Thus URL Encoding Model Attribute

Original route went to /{id}, and I changed the route to /{name}

In the view, I iterate over the particular model, leading to this blade html:

<a href="{{ route('modelHistory', urlencode(strtolower($model->name)) ) }}">
                                  {{$model->name}}
                                </a>

And then I had some code in the Controller to reconvert the name passed to the route into a name that matches what’s in the database.

Laravel, somehow, sucked the urlencode and strtolower code into itself, possibly the middleware, such that any retrieval of Model::all gave us a name that was urlencoded and all lowercase.

It became an issue, because I wanted to change URL to be the name converted to lowercase with underscores instead of urlencoded, but the names remained urlencoded and lowercased, which was a problem when another view lists all instances of Model and surfaces the name attribute.

Solution below.


Source: stackoverflow-php

Dropzone with laravel

I am using dropzone.js with laravel to upload photos, it works perfectly.
I also added remove link for each photo. during uploading process I change the name of photo using time(). and save it into database.

My question is how I can get the new name of photo , so I can use it when I want to remove it using dropzone.js

Many thanks and best regards,


Source: stackoverflow-php

Carbon date saves as 0000-00-00 in Laravel

I am trying to save a date in Laravel, but it keeps defaulting to 0000-00-00.

Migrations setup:

$table->date('audit_date')->nullable();

It needs to be nullable because it’s not initially added, this function edits the row.

Controller:

$date = Carbon::createFromFormat('d/m/Y', $request->get('datepicker'))
            ->toDateString();

If I output the $date, it shows "2017-03-16"

Full snippet showing where the date is added:

$date = Carbon::createFromFormat('d/m/Y', $request->get('datepicker'))
           ->toDateString();

    $audit = Score::where('id', 1)->first();
    $audit->audited = 1;
    $audit->audit_date = $date;
    $audit->save();

Why does it save as 0000-00-00?


Source: stackoverflow-php

Can’t access object property in Laravel

I started learning Laravel since yesterday and face some difficulties to get property of an object.

Here is the class (created with artisan) :

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Task extends Model
{
    public $description;
    public $completed;
    public $timestamps = false;

    public function isComplete()
    {
        return $this->completed;
    }
}

And here is the issue :

>>> $tasks = AppTask::all();
=> IlluminateDatabaseEloquentCollection {#654
     all: [
       AppTask {#652
         id: "1",
         description: "Learn Laravel",
         completed: "0",
       },
     ],
   }
>>> $tasks[0]->id
=> 1
>>> $tasks[0]->description
=> null

Why can I access the id but not the description ?


Source: stackoverflow-php

auto-injected Laravel model has no attributes

I’m new to Laravel. I have created a model, a resource controller, and a route for one of my tables, I have modified the model class to use a particular table name, but the model object injected by Laravel 5.4 has no attributes even though a corresponding record exists in the database. Here are the steps I took.

1) Create the model with artisan. I ran this command:

php artisan make:model Tree

2) Modify the Tree model class as instructed to specify a specific table. I had to do this because my table is named tree, not the “trees” as Laravel would otherwise assume based on its internal rules.

/**
 * The table associated with the model.
 *
 * @var string
 */
protected $table = 'tree';

3) Create a resource controller that makes use of my model with this command

php artisan make:controller CategoryController --resource --model=Tree

4) Add a resource route routes/web.php in order to map a web server path onto the controller:

Route::resource('categories', 'CategoryController');

5) Modify the show() method of the CategoryController to var_dump the injected $tree object. It looks like this:

/**
 * Display the specified resource.
 *
 * @param  AppTree  $tree
 * @return IlluminateHttpResponse
 */
public function show(Tree $tree)
{
    // we need to display the children of $tree
    var_dump($tree);

}

6) My table structure follows all the conventions specified by Laravel docs. There is an integer id column that is unsigned & auto-incrementing. I have the created_at and updated_at timestamps. The only thing different is that the table name is “tree” and not “trees”, but that should be covered with the change I made above:

CREATE TABLE IF NOT EXISTS `tree` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `parent_id` int(10) unsigned DEFAULT NULL,
  `label` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `display_order` int(11) unsigned NOT NULL DEFAULT '0',
  `forum_id` int(5) NOT NULL DEFAULT '0',
  `url` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `flavor` tinyint(4) NOT NULL DEFAULT '0',
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `parent_pkey` (`parent_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

This table contains data. It most definitely has a record with id=1.

7) I visit the url which should activate the show() method of my resource controller. The output I get verfies that this is in fact the method CategoryController::show(). http://example.com/categories/1

Here is the problem.

The output of var_dump($tree) has no attributes. There is no error, but something is wrong with the injected object.

object(AppTree)#217 (24) {
  ["table":protected]=>
  string(4) "tree"
  ["connection":protected]=>
  NULL
  ["primaryKey":protected]=>
  string(2) "id"
  ["keyType":protected]=>
  string(3) "int"
  ["incrementing"]=>
  bool(true)
  ["with":protected]=>
  array(0) {
  }
  ["perPage":protected]=>
  int(15)
  ["exists"]=>
  bool(false)
  ["wasRecentlyCreated"]=>
  bool(false)
  ["attributes":protected]=>
  array(0) {
  }
  ["original":protected]=>
  array(0) {
  }
  ["casts":protected]=>
  array(0) {
  }
  ["dates":protected]=>
  array(0) {
  }
  ["dateFormat":protected]=>
  NULL
  ["appends":protected]=>
  array(0) {
  }
  ["events":protected]=>
  array(0) {
  }
  ["observables":protected]=>
  array(0) {
  }
  ["relations":protected]=>
  array(0) {
  }
  ["touches":protected]=>
  array(0) {
  }
  ["timestamps"]=>
  bool(true)
  ["hidden":protected]=>
  array(0) {
  }
  ["visible":protected]=>
  array(0) {
  }
  ["fillable":protected]=>
  array(0) {
  }
  ["guarded":protected]=>
  array(1) {
    [0]=>
    string(1) "*"
  }
}

Have I done something wrong? How do I get Laravel to inject the correct object?


Source: stackoverflow-php

Laravel 5.4 post request token mismatch

I am learning to create API in Laravel. I created a CRUD controller, and I have an empty store function:

public function store(Request $request)
{
    dd('store');
}

When I try to make a post request with Postman I get the token mismatch exception:

"IlluminateSessionTokenMismatchException">TokenMismatchException in
   "/Users/andrei/Desktop/api.dev/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php line 68">VerifyCsrfToken.php line 68

I have no form for the post method to put {{csrf.. }}. How can this be solved? Thank you!


Source: stackoverflow-php

How do I allow multiple many-to-many entries in laravel?

In my Laravel5 app I have users, tasks, and user_tasks. A user can complete a task multiple times:

User:
  id
  name
  ...

Task:
  id
  name
  value
  ...

UserTask:
  id
  user_id
  task_id
  completed_on

If this were a normal many-to-many relationship I would have this function in the user class:

class User extends Model {
  // ...
  public function tasks(){
    return $this->belongsToMany(Task::class, 'user_tasks', 'user_id', 'task_id');
  }
}

But I believe this means that user_id/task_id is a primary key on user_tasks. How do I change the relationships between Task and User if I want duplicate user_id/task_id entries in the join table?

Second question, what if I want a list of all unique tasks a user has completed, regardless of how many time a user has completed them?


Source: stackoverflow-php

The @ sign in Laravel web.php route files

What exactly the ‘@’ sign stand for in laravel route file web.php
Ex: Route::get(‘/’, ‘HomeController@index’);? please don’t tell me what this code does I already know that. but the question is why the @ sign??
The’@’ sign is not a method but the index is. so what is name of this @ sign and what exactly it does? I’m just curious to know why??? the @ sign.


Source: stackoverflow-php