lundi 5 décembre 2016

How to temporarily hide model relations attributes with Laravel 5

I have read how to temporarily hide model attributes. I would like to temporarily hide a model relation attribute.

For instance

{
    "slug": "google-chrome",
    "name": "Google Chrome",
    "description": {
         "text": null,
         "created_at": "2016-12-05 12:16:38",
         "updated_at": "2016-12-05 12:16:38"
}

What is the syntax for hiding the description.created_at only in this query? In my SoftwareController I have

public function show(Request $request, $slug)
{
    $models = Software::query();

    $model =
        $models
        ->where('slug', $slug)
        ->firstOrFail()
        ->makeHidden([
            'description.created_at',
        ]);

    return $model;
}

This syntax does not seem to work? Is it possible?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2gZOtBp
via IFTTT

PHP Laravel API test failure unexplained

I am following a tutorial PluralSight by Stephen Macguire "Play by Play: Getting Started with Laravel 5", the code for which is on GitHub http://ift.tt/2gITLk5.

(However, the code below is slightly different from the code on GitHub. The code on Git Hub has the line in the test:

$this->post(route('api.products.store'), $product->jsonSerialize(), $this->jsonHeaders)

In my test the code has the line:

$this->post(route('api.products.store'), $product->jsonSerialize())

My other tests post without the "$this->jsonHeaders" successfully and this does not give the error.)

I am running a test to confirm that when I try to post a request to create a product with an empty name, that the JSON response has 'The name field is required.' Moreover the status of the of the response should be 422 - Unprocessable Entity.

However, though the ProductController validates that the name is required:

class ProductController extends Controller
{
    public function index() {
      return Product::paginate();
    }

    public function store(Request $request)
    {
      $this->validate($request, [
          'name' => 'required|unique:products',
      ]);

      return Product::create([
        'name' => $request->input('name')
      ]);
    }

    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'name' => 'required|unique:products',
        ]);
        $product = Product::findOrFail($id);
        $product->update([
            'name' => $request->input('name')
        ]);
        return $product;
    }
}

The test that fails is as follows:

public function testCreateProductFailsIfNameNotProvided()
    {
        $product = factory(Product::class)->make(['name' => '']);

        $this->post(route('products.store'), $product->jsonSerialize())
             ->seeJson(['name' => ['The name field is required.']])
             ->assertResponseStatus(422);
    }

The testing is command line phpunit with the following output:

There was 1 failure:

1) ExampleTest::testCreateProductFailsIfNameNotProvided
Invalid JSON was returned from the route. Perhaps an exception was thrown?

/home/vagrant/projects/demo/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:426
/home/vagrant/projects/demo/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:298
/home/vagrant/projects/demo/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:324
/home/vagrant/projects/demo/tests/ExampleTest.php:74

If the "->seeJson" line in the test is commented off the following failure is recorded:

1) ExampleTest::testCreateProductFailsIfNameNotProvided
Expected status code 422, got 302.
Failed asserting that 302 matches expected 422.

/home/vagrant/projects/demo/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:744
/home/vagrant/projects/demo/tests/ExampleTest.php:75

Laravel Framework version 5.3.26, testing phpunit, Laravel Homestead in Vagrant Box running in VM VirtualBox



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2g33g9I
via IFTTT

Laravel 5.3 Ajax Request 405 error

This is the first time I am trying AJAX and the API routes file within laravel 5.3. I am currently just trying to make a simple AJAX call to make sure I can get everything working and know how to continue in future. However, I keep getting 405 errors and I am not sure what I am doing wrong. This is what i have currently: My api.php route folder:

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::group(['middleware' => ['auth:api']], function () {
Route::post('/test', function (Request $request) {
  return response()->json(['name' => 'test']);
});
});

And my ajax call:

<script src="http://ift.tt/2dletCP"
  integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA="
  crossorigin="anonymous"></script>
<meta name="csrf-token" content="" />
<script type="text/javascript">
                var CSRF_TOKEN = jQuery('meta[name="csrf-token"]').attr('content');

      jQuery.ajax({
           url: '/api/test/',
           type: 'POST',
           data: {_token: CSRF_TOKEN},
           dataType: 'JSON',
           success: function (data) {
           console.log(data);
           }
        });
    </script>



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2haT9VA
via IFTTT

Cron job is running two different commands : Laravel 5

My command on godaddy server for Cron job is below.

/usr/local/bin/php -q public_html/Publisher/artisan schedule:run > /dev/null 2>&1

My app\Console\Kernel.php is here

class Kernel extends ConsoleKernel
{
    protected $commands = [
        'App\Console\Commands\ytzAPI',
        'App\Console\Commands\Invoice',
    ];

    protected function schedule(Schedule $schedule)
    {
        $schedule->command('api:ytz')->everyMinute();
        $schedule->command('api:invoice')->daily();
    }

    protected function commands()
    {
        require base_path('routes/console.php');
    }
}

My Question

I want to run one command after every minute and another command on daily basis.

$schedule->command('api:ytz')->everyMinute();
$schedule->command('api:invoice')->daily();

Cron job is running after each minute and is running $schedule->command('api:invoice')->daily(); also. How could I differentiate everyMinute command from daily



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2h702Dl
via IFTTT

barryvdh/laravel-cors not working for my routes

I'm using [this laravel-cors package][1], I've read the docs and I've added the service provider to config/app.php.

After adding the middleware to kernel.php like so:

  protected $middleware = [
  \Barryvdh\Cors\HandleCors::class,
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,

];

It works for my passport routes, but not for my own routes.

Passport routes

Route::group([
        'middleware' => ['api']
    ], function ($router) {
        Passport::routes();
        Passport::tokensExpireIn(Carbon::now()->addDays(15));
        Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));
    });

My routes

Route::group(['middleware' => ['auth:api']], function () {


Route::resource('answers', 'AnswersController');
});



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2gubxVf
via IFTTT

How to register more than one type of users and how to make multi auth in laravel 5.3

Maybe someone will notice that I'm asking this question again but I have reason for that. I have asked two questions before about this problem and I didn't find any good еxplanation and answer..

How to make two types of users in Laravel

Register new type of user in Laravel 5.3

I will try to explain better now what is my question in general. I'm trying to register two types of users, and my idea is to have two different tables for that users, and the second problem that I have is how to make multi authentication after I register the user on one same login form.

I'm searching for answers for long time and I didn't find any good answer.

Thank you very much!



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2ham788
via IFTTT

Laravel Eloquent relationship data hidden in response

I have two models: User and Group. A user can be a member of just one group, and a group can have multiple users:

User:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $table = 'user';
    protected $primaryKey = 'user_id';

    protected $fillable = [];
    protected $visible = ['user_id', 'name', 'points', 'group_id', 'profile'];


    /**
     * Get group where user belongs to
     */
    public function group()
    {
        return $this->belongsTo('App\Models\Group', 'group_id', 'group_id');
    }
}

Group:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Group extends Model
{
    protected $table = 'group';
    protected $primaryKey = 'group_id';

    protected $fillable = [];
    protected $visible = ['group_id', 'name', 'profile'];

    /**
     * Get all group users.
     */
    public function users()
    {
        return $this->hasMany('App\Models\User', 'group_id', 'group_id');
    }
}

Now in my controller, I want to retrieve the user data and the users' group data. Therefore I use this:

$users = User::with('group')
        ->orderBy('points', 'DESC')
        ->take(50)
        ->get();

return response()->json($users);

So far so good. I expect the above to return something like this:

[
  {
    "user_id": 27,
    "name": "linnie15",
    "points": 18565,
    "group_id": 6,
    "profile": null,
    "group": {
      "group_id": 6,
      "name": "White Wall",
      "profile": "Et tempore voluptatibus sunt ratione ut. Eum sint mollitia omnis eius ut facilis aut. Sed quisquam quis velit qui sint soluta. Autem quia ipsam esse sapiente delectus vel."
    }
  },
]

But, here is the problem. The only thing it returns is this:

[
  {
    "user_id": 27,
    "name": "linnie15",
    "points": 18565,
    "group_id": 6,
    "profile": null
  },
]

How is that possible? In fact, I found the solution, by adding 'group' to the $visible array in the User model. But why is that? I mean, should I really add all my relationships to the $visible array? Why would that be necessary. If you query a relationship, you always want the result, isn't it?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2h6zBh5
via IFTTT