rodrigo.pedra

rodrigo.pedra

Lead Developer at avaliadora.com.br

Member Since 5 Years Ago

São Carlos, Brazil

Experience Points
223,330
Total
Experience

1,670 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
1027
Lessons
Completed
Best Reply Awards
178
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 45
223,330 XP
Jul
11
2 days ago
Activity icon

Replied to How To Start

I would highly recommend starting with this series:

https://laracasts.com/series/laravel-6-from-scratch

It is a free series and covers basically all you need to know to get started with Laravel.

Although Laravel current version is v7 and the series is named after v6, the concepts covered in that series have not changed a lot and most code should work on v7 with no changes.

v7 introduced some new features worth taking a look such as the HTTP client and blade components, but after going through that series you can easily learn those from the docs itself:

https://laravel.com/docs

Those content are also covered in some other Laracasts videos, specially blade components have an on going series:

https://laracasts.com/series/blade-component-cookbook

But this one is not free to watch.

Jun
09
1 month ago
Activity icon

Replied to Laravel Mysql Select All Except An Array Of Values ?

It seems your frontend is sending mat_codes as an string with the codes concatenated by a string.

Try this:

$mat_codes = [];

if ($request->mat_codes !== null) {
    $mat_codes = explode(',', $mat_codes);
}

It doesn't seem that the mat_codes request variables can contain spaces between commas, but if that is a possibility, I would add:

$mat_codes = [];

if ($request->mat_codes !== null) {
    $mat_codes = array_map('trim', explode(',', $mat_codes));
}

Just to be sure if an element on the list contains a space, such as xxx, 123, it becomes the array ['xxx', '123']

May
03
2 months ago
Activity icon

Awarded Best Reply on Calling Validation FormRequest From Controller Is Sometimes Incorrect

Unfortunately passing arguments to class hints is not possible.

As FormRequest is a Request you don't need to use the request() helper inside of it. You could change your example as the following:

protected function prepareForValidation()
{
    if (!$this->has('enable')) return; // do nothing

    // process as above
}

Also you could have a QuickAddTasksRequest with the rules method and make TaskRequest extend that adding the prepareForValidation method.

Personally I avoid having deep class hierarchies, as they can become hard to maintain, but that is an option.

For example:

// namespace, use, etc...

class QuickAddTasksRequest extends FormRequest {
  public function rules() {
    return [
      // validation rules
    ];
  }

  // no prepareForValidation
}
// namespace, use, etc...

class TasksRequest extends QuickAddTasksRequest {
  // no need of a rules method as they are defined in the parent class

  public function prepareForValidation() {
    // pre-validation sanitizing logic
  }
}

And then on each controller you would have:

// quick add controller

public function store(QuickAddTasksRequest $request) {
  $validated = $request->validated();
  // do something with the validated data
}
// regular controller

public function store(TasksRequest $request) {
  $validated = $request->validated();
  // do something with the validated data
}

That way the prepareForValidation method would only be executed in the TasksRequest while it shares the same rules from the QuickAddTasksRequest

May
02
2 months ago
Activity icon

Replied to Hide Modal Box After User Login

As you are using standard bootstrap data- attributes I assume you have jQuery in your setup.

So you can manually hide the modal after the user logs in:

      submit () {
        this.signIn(this.form);
        $('#myModal1').modal('hide');
      }

Reference

https://getbootstrap.com/docs/4.4/components/modal/#modalhide

Activity icon

Replied to Calling Validation FormRequest From Controller Is Sometimes Incorrect

Unfortunately passing arguments to class hints is not possible.

As FormRequest is a Request you don't need to use the request() helper inside of it. You could change your example as the following:

protected function prepareForValidation()
{
    if (!$this->has('enable')) return; // do nothing

    // process as above
}

Also you could have a QuickAddTasksRequest with the rules method and make TaskRequest extend that adding the prepareForValidation method.

Personally I avoid having deep class hierarchies, as they can become hard to maintain, but that is an option.

For example:

// namespace, use, etc...

class QuickAddTasksRequest extends FormRequest {
  public function rules() {
    return [
      // validation rules
    ];
  }

  // no prepareForValidation
}
// namespace, use, etc...

class TasksRequest extends QuickAddTasksRequest {
  // no need of a rules method as they are defined in the parent class

  public function prepareForValidation() {
    // pre-validation sanitizing logic
  }
}

And then on each controller you would have:

// quick add controller

public function store(QuickAddTasksRequest $request) {
  $validated = $request->validated();
  // do something with the validated data
}
// regular controller

public function store(TasksRequest $request) {
  $validated = $request->validated();
  // do something with the validated data
}

That way the prepareForValidation method would only be executed in the TasksRequest while it shares the same rules from the QuickAddTasksRequest

Activity icon

Awarded Best Reply on Problem With Storing Checkbox Values In Database

If you want the checkboxes values as an array the name attribute in all of them should something like name="looking_for[]" so PHP will make them available as an array.

Also the for attribute in the <label> element binds the label to a input by its id attribute. id is the one that should be unique in a HTML document. name tells how to pack the form input fields when submitting

<div class="interestedIn">
  <input type="checkbox" id="{{ $name.'-'.$value }}" name="{{ $name }}[]" value="{{ $value }}" {{ isset($data[$fieldData['label']['id']]) ? (in_array($value, $data[$fieldData['label']['id']]) ? 'checked' : null) : '' }}>
  <label for="{{$name}}-{{ $value }}">{{ $label }}</label>
</div>

Note: Just added id and changed name, didn't assessed nor changed your checked logic

Activity icon

Replied to Problem With Storing Checkbox Values In Database

If you want the checkboxes values as an array the name attribute in all of them should something like name="looking_for[]" so PHP will make them available as an array.

Also the for attribute in the <label> element binds the label to a input by its id attribute. id is the one that should be unique in a HTML document. name tells how to pack the form input fields when submitting

<div class="interestedIn">
  <input type="checkbox" id="{{ $name.'-'.$value }}" name="{{ $name }}[]" value="{{ $value }}" {{ isset($data[$fieldData['label']['id']]) ? (in_array($value, $data[$fieldData['label']['id']]) ? 'checked' : null) : '' }}>
  <label for="{{$name}}-{{ $value }}">{{ $label }}</label>
</div>

Note: Just added id and changed name, didn't assessed nor changed your checked logic

Activity icon

Replied to Can I Use Laravel Educational Projects?

Sure. Sorry for the late response, was busy these last days.

Activity icon

Replied to Calling Validation FormRequest From Controller Is Sometimes Incorrect

Sorry for the late response, these last days were busy to me.

As the form request extends the request you have access to all the normal request's methods.

For example you could check by route name:

protected function prepareForValidation()
{
    if ($this->routeIs('my.route.name')) return; // do nothing

    // process as above
}

by path:

protected function prepareForValidation()
{
    if ($this->is('/task/*')) return; // do nothing

    // process as above
}

Or by any other request method.

Activity icon

Awarded Best Reply on Get Type SET Values Using Eloquent.

You mean to discover from an existing DB?

I would list them in a constant in a Model class, as querying the DB every time to check for valid values can lead to performance issues, also SET values generally don't change too much.

Anyway, I found this link that gets the value for a ENUM column, might help you somehow.

http://constituteweb.com/eloquent-laravel-enum

Apr
29
2 months ago
Activity icon

Replied to Can I Use Laravel Educational Projects?

You're welcome =) hope something helps.

Activity icon

Replied to Multi Threading In Laravel

I guess you can enable threads if you are using php-fpm (usually with nginx) but you will need to whitelist and increase timeout in your php.ini

I wouldn't go that way, as it is not usual.

But considering your description I would agree that the options are using queued jobs or optimized synchronous code.

Personally I like the flow of queuing jobs and have a record to inform the user of the progress and completion/failure. I think UI is more responsive as the request just dispatches the job and gets back to the user.

But of course your requirements might ask for a different approach.

Good luck, and please share if you come to a different strategy.

Activity icon

Replied to Calling Validation FormRequest From Controller Is Sometimes Incorrect

You can override the prepareForValidation method from the form request to merge data before the Form Request validation is triggered

https://laravel.com/docs/7.x/validation#prepare-input-for-validation

Even the example from the docs is something similar:

/**
 * Prepare the data for validation.
 *
 * @return void
 */
protected function prepareForValidation()
{
    $this->merge([
        'slug' => Str::slug($this->slug),
    ]);
}

In your case it would be something like this:

protected function prepareForValidation()
{
    // get accepts a default value when field is not present
    // also, as FormRequest extends request we can use $this here
    $id = $this->get('id', 0);

    $suggest = TasksSuggests::find( $id );

    $data = /* ... init data from suggest */

    $this->merge($data);
}

This prepareForValidation will be called before the form request validation is triggered.

Apr
28
2 months ago
Activity icon

Replied to [FormRequest Validation] Missing Inputs Marked Required Not Validating

If you add a required attribute to the <select> element the HTML form won't allow the user to submit it if a value is not chosen:

<select name="category" required>
	<option value="">Select a category</option>
</select>
Activity icon

Awarded Best Reply on Using Route Helper Links With Tabbed Nav Bar Pills

From my understanding one would use the data-toggle behavior when they already have the content rendered and only want to show a tab at a time. So it makes sense to prevent the link to do navigation.

It seems that you want to navigate between different pages but have the correct tab highlighted. If that is the case, you can change the active class to the selected link:

<nav class="navbar navbar-expand-sm fixed-top navbar-light bg-white ">
    <div class="container-fluid">
        <ul class="nav nav-pills nav-pills -primary nav-pills -icons justify -content -center" role="tablist">
            <li class="nav-item" style="padding -right:0.9em;">
                <a class="nav-link {{ request()->routeIs('user.index') ? 'active' : null }}" href="{{ route('user.index') }}" role="tablist">User </a>
            </li>
            <li class="nav-item">
                <a class="nav-link {{ request()->routeIs('page.charts') ? 'active' : null }}"  href="{{ route('page.charts') }}" role="tablist" margin="30px">Charts </a>
            </li>
        </ul>
    </div>
</nav>
Activity icon

Replied to [FormRequest Validation] Missing Inputs Marked Required Not Validating

Really weird, I just tested with a clean laravel install with this form request and route:

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

class DummyRequest extends FormRequest
{
    public function rules()
    {
        return [
            'name' => 'required',
            'category' => 'required',
        ];
    }

    protected function failedValidation(Validator $validator)
    {
        $response = response()->json($this->all() + ['failed' => true]);

        throw new HttpResponseException($response);
    }
}
Route::get('test', function (\App\Http\Requests\DummyRequest $request) {
    return $request->all() + ['valid' => true];
});

So if I navigate to one of these:

http://localhost:8000/test
http://localhost:8000/test?name=Mary
http://localhost:8000/test?category=Dev

It shows the 'failed' key on the output as expected, and when navigating to

http://localhost:8000/test?name=Mary&category=Dev

It shows the 'valid' key on the output as expected.

So it seems your problem might something else, but it is hard to tell with the information we have.

I would double check the data coming to the request adding a dd() to the FormRequest's validated method:


public function validated()
{
    dd(parent::validated(), $this->all());
}

Just to be sure category is missing from the request when it passes.

Activity icon

Replied to Multi Threading In Laravel

You can have an auxiliary table/model where you track your job status and save the results. So in the frontend you would show the processing status while it processes and keep refreshing (or polling with ajax) the status until it is done.

Imagine you need to perform time expensive operations on an Order model. Your job would be something like this:

class GenerateExpensiveReport implements ShouldQueue {
  use SerializesModels;

  protected $order;

  // pass any other needed variables to the job
  public function __construct(Order $order) {
    $this->order = $order;
  }

  public function handle() {
    $process = new Process();
    $process->status = 'processing';
    $process->output = null;
    $process->started_at = now();
    $process->ended_at = null;
    $this->order->process()->save($process);

    try {
      // perform some time expensive calculation

      $process->status = 'success';
      $process->output = null;
      $process->ended_at = now();
      $process->save();
    } catch(\Throwable $exception) { // use \Exception on older PHP version
      $process->status = 'error';
      $process->output = $exception->getMessage();
      $process->ended_at = now();
      $process->save();
    }
  }
}

The Process model needs a table with a status, output, started_at and ended_at and morph columns.

https://laravel.com/docs/7.x/eloquent-relationships#one-to-one-polymorphic-relations

And in your Order model you define the relation to process as this:

public function process()
{
  return $this->morphOne(Process::class, 'processable')
    ->withDefault(function () {
      return Process(['status' => 'pending']);
    });
}

Of course you can add those snippets to update a process status on the status model itself so you can reuse with other jobs

Activity icon

Awarded Best Reply on Is It Best Practice If I Store Model Data In $request?

Don't worry, having path-related parameters bound to the request object is a common practice.

Laravel even has this feature (automatically bind a model based on a route parameter) out of the box:

https://laravel.com/docs/7.x/routing#route-model-binding

It is a very useful feature.

If you are using Laravel 7 you can skip your middleware and change your routes paths to:

/{member:code}/abc

/{member:code}/def

/{member:code}/xyz

Then in your controllers/action do this:

$member = $request->route('member');

Laravel will even throw a 404 when member is not found.

Activity icon

Awarded Best Reply on How Can I Write Shorter This?

return response()->json([
  'movie' => $movie,
  'watched' => $movie->usersWhoWatched()->where('user_id', auth()->user()->id)->exists(),
]);

No need to add 200 (it is the default value) and moved the condition directly to the returned array.

Activity icon

Replied to How Can I Write Shorter This?

return response()->json([
  'movie' => $movie,
  'watched' => $movie->usersWhoWatched()->where('user_id', auth()->user()->id)->exists(),
]);

No need to add 200 (it is the default value) and moved the condition directly to the returned array.

Activity icon

Replied to Using Route Helper Links With Tabbed Nav Bar Pills

From my understanding one would use the data-toggle behavior when they already have the content rendered and only want to show a tab at a time. So it makes sense to prevent the link to do navigation.

It seems that you want to navigate between different pages but have the correct tab highlighted. If that is the case, you can change the active class to the selected link:

<nav class="navbar navbar-expand-sm fixed-top navbar-light bg-white ">
    <div class="container-fluid">
        <ul class="nav nav-pills nav-pills -primary nav-pills -icons justify -content -center" role="tablist">
            <li class="nav-item" style="padding -right:0.9em;">
                <a class="nav-link {{ request()->routeIs('user.index') ? 'active' : null }}" href="{{ route('user.index') }}" role="tablist">User </a>
            </li>
            <li class="nav-item">
                <a class="nav-link {{ request()->routeIs('page.charts') ? 'active' : null }}"  href="{{ route('page.charts') }}" role="tablist" margin="30px">Charts </a>
            </li>
        </ul>
    </div>
</nav>
Activity icon

Replied to Is It Best Practice If I Store Model Data In $request?

Don't worry, having path-related parameters bound to the request object is a common practice.

Laravel even has this feature (automatically bind a model based on a route parameter) out of the box:

https://laravel.com/docs/7.x/routing#route-model-binding

It is a very useful feature.

If you are using Laravel 7 you can skip your middleware and change your routes paths to:

/{member:code}/abc

/{member:code}/def

/{member:code}/xyz

Then in your controllers/action do this:

$member = $request->route('member');

Laravel will even throw a 404 when member is not found.

Activity icon

Replied to Contact Form Not Passing Data To Database?

It seems Mass Assignment is preventing the data to be saved on your Contact model. Take a look in the docs:

https://laravel.com/docs/7.x/eloquent#mass-assignment

So you either white-list the attributes you want to allow to be mass-assigned or you can disable this protection:

1. White-listing

class Contact extends Model {
  protected $fillable = ['name', 'email', 'text'];
}

2. Disable

class Contact extends Model {
  protected $guarded = [];
}
Activity icon

Replied to Object Of Class Generator Could Not Be Converted To String

You're welcome =) Glad to help

Activity icon

Awarded Best Reply on Object Of Class Generator Could Not Be Converted To String

From the package readme file:

a Generator is returned by default. If you want an array instead, you can set the third parameter of the generate method to true. If you want to generate one code based on one number, you only have to set the first parameter of the generate method.

So in your case you need to change the ->generate(1, 100) call to something like ->generate(1)

Also from the package's readme:

Each number will always generate the same unique, random-looking code.

So using ->generate(1) will always yield the same code, which I assume is not what you want. Therefore you should provide a unique number per record.

If your Courses model has an auto-increment ID, you could update after saving:

    $course = new Courses();
    
    // assign  a temporary code if the columns is defined as not null
    $course->numero = 'TEMP';
    $course->idclient = $request->input('idclient');
    $course->idcoursier = $request->input('idcoursier');
    $course->pointdep = $request->input('pointdep');
    $course->destination = $request->input('destination');
    $course->type = $request->input('type');
    $course->nbrbon = $request->input('nbrbon');
    $course->daterecup = $request->input('daterecup');
    $course->heurerecup = $request->input('heurerecup');
    $course->description = $request->input('description');
    $course->save(); // saving will generate a new id

    
    $course->numero = (new UniqueCodes())
    ->setPrime(184259)
    ->setMaxPrime(7230323)
    ->setCharacters('LQJCKZM4WDPT69S7XRGANY23VBH58F1')
    ->setLength(6)
    ->generate($course->id); // use the newly generated ID
    $course->save(); // save it again

    return redirect('/admin/courses')->with('status1',' ');
Activity icon

Replied to Multi Threading In Laravel

You can move the heavy computation to a job and dispatch this job to a queue for background processing.

https://laravel.com/docs/7.x/queues#creating-jobs

https://laravel.com/docs/7.x/queues#introduction

Activity icon

Replied to Object Of Class Generator Could Not Be Converted To String

From the package readme file:

a Generator is returned by default. If you want an array instead, you can set the third parameter of the generate method to true. If you want to generate one code based on one number, you only have to set the first parameter of the generate method.

So in your case you need to change the ->generate(1, 100) call to something like ->generate(1)

Also from the package's readme:

Each number will always generate the same unique, random-looking code.

So using ->generate(1) will always yield the same code, which I assume is not what you want. Therefore you should provide a unique number per record.

If your Courses model has an auto-increment ID, you could update after saving:

    $course = new Courses();
    
    // assign  a temporary code if the columns is defined as not null
    $course->numero = 'TEMP';
    $course->idclient = $request->input('idclient');
    $course->idcoursier = $request->input('idcoursier');
    $course->pointdep = $request->input('pointdep');
    $course->destination = $request->input('destination');
    $course->type = $request->input('type');
    $course->nbrbon = $request->input('nbrbon');
    $course->daterecup = $request->input('daterecup');
    $course->heurerecup = $request->input('heurerecup');
    $course->description = $request->input('description');
    $course->save(); // saving will generate a new id

    
    $course->numero = (new UniqueCodes())
    ->setPrime(184259)
    ->setMaxPrime(7230323)
    ->setCharacters('LQJCKZM4WDPT69S7XRGANY23VBH58F1')
    ->setLength(6)
    ->generate($course->id); // use the newly generated ID
    $course->save(); // save it again

    return redirect('/admin/courses')->with('status1',' ');
Activity icon

Replied to Calling Validation FormRequest From Controller Is Sometimes Incorrect

As you are reusing all the methods from the TasksRequest, and even replacing the request validator with a TaskRequest instance, why not type-hinting it directly on this API controller?

Something like this:

public function store(\App\Requests\TasksRequest $request) {
  $result = $this->create( $request->validated() );

  return $result;
}

One thing that might be different is the authorize method, if that is the case you can extend TasksRequest and override just the authorize method:

class ApiTasksRequest extends TasksRequest {
  public function authorize() {
    // handle API authorization
  }

  // rules and messages will be inherited from TasksRequest
}

Then you would just need to type-hint it:

public function store(\App\Requests\ApiTasksRequest $request) {
  $result = $this->create( $request->validated() );

  return $result;
}
Activity icon

Replied to [FormRequest Validation] Missing Inputs Marked Required Not Validating

Can you share some code? Such as the rules method from your FormRequest class?

I use FormRequests a lot in my projects and never faced such situation you are describing.

Activity icon

Replied to Can I Use Laravel Educational Projects?

Hi @ergali

Laravel is a fullstack general-purpose framework.

Being fullstack means it has features to allow handling both frontend and backend needs inside the framework. Of course you can still use your preferred JavaScript framework, but Laravel has enough features to build a powerful and dynamic frontend without needing one.

Being general-purpose means that you can build almost anything you want with it. It is not oriented to a specific purpose. For example Worpress is target to CMS (Content Managements Systems), so implementing applications which are not content-oriented with Wordpress would require you to fight against the framework in some cases.

Being general-purpose also means that it lacks some out-of-the box features specific to a more specific context. For example, Wordpress, being a CMS, has database-schema and UI in place for managing blog posts and related content out-of-the-box. Laravel lacks any of those features. (It has some first-party packages/addons that provide some features such as Social Login, payment gateway integration, and others).

In your case you would need to code, or to use a package/addon to build the business requirements of the educational workflow you described.

It handles large datasets very well, I would suggest you learn about using queues for background processing and deferring time consuming tasks such as report consolidation and interacting with other services such as sending emails.

Of course all comes down to how much time and resources you have available, as you will have to code your project requirements or to learn how to integrate one or more packages that provide the features you need.

If your concern is about performance, scale, and automation capabilities, I would say Laravel is a good choice.

If your biggest constraint is time and you cannot afford the time to learn how to build all the requirements you need, I would suggest you to look after some opens-source LMS (Learning Management Systems) platforms such as Canvas-LMS, Moodle, or others. (As Canvas is AGPL licensed, your University might need a commercial license before using it in production, please take a look into this aspect).

The biggest con on using a pre-built platform is when you need to customize, or change a pre-built workflow. Also these targeted-purpose platforms might lack some aspects from your requirements such as payment management. You could use one of those for the educational aspect and implement a Laravel-based app to add any missing features.

Apr
27
2 months ago
Activity icon

Awarded Best Reply on Pagination Data Missing From Api Resource.

It seems this is due to changes here: https://github.com/laravel/framework/pull/30801

So by that PR description, previously when calling ->toJson() the call would be forwarded to the underlying resource.

So you might expect a different output from 7.x resources when using paginated data. One difference is that paginalition links are under a meta property. Actually this was already done in previous versions when returning the resource as a response instead of calling its ->toJson() method.

You can try doing this:

dd($resource->response()->getData())

This will convert the Resource to a Response object and getData will use json_decode to decode the response's content back.

If you want the payload to be decoded as an associative array use this:

dd($resource->response()->getData(true))

And if you want the raw decoded JSON payload use this instead:

dd($resource->response()->getContent())
Activity icon

Replied to Pagination Data Missing From Api Resource.

It seems this is due to changes here: https://github.com/laravel/framework/pull/30801

So by that PR description, previously when calling ->toJson() the call would be forwarded to the underlying resource.

So you might expect a different output from 7.x resources when using paginated data. One difference is that paginalition links are under a meta property. Actually this was already done in previous versions when returning the resource as a response instead of calling its ->toJson() method.

You can try doing this:

dd($resource->response()->getData())

This will convert the Resource to a Response object and getData will use json_decode to decode the response's content back.

If you want the payload to be decoded as an associative array use this:

dd($resource->response()->getData(true))

And if you want the raw decoded JSON payload use this instead:

dd($resource->response()->getContent())
Mar
27
3 months ago
Activity icon

Awarded Best Reply on Visual Math Editor

As the documentation says it manipulates a <textarea> I guess so. Just add a name attribute and a standard <form> would send it without a problem.

If you are fine with user inputting LaTeX syntax directly them you have more options. Check this wikipedia comparison table for many editors:

https://en.wikipedia.org/wiki/Formula_editor

There's a column for platform (check for web) and also a column for open source. Note that not being open source does not mean it is not free, although it is likely that most non-opensource options there are paid/licensed.

Mar
23
3 months ago
Activity icon

Replied to How To Login With Different Models In Laravel?

You're welcome =) Hope it helps.

Activity icon

Awarded Best Reply on How To Login With Different Models In Laravel?

Will both models access the same resources?

For example, both will have access to the same protected routes? (/homepage, etc.)

If yes, I guess you are better using a single model, at least for authentication. You can have a User model that holds auth related stuff (email and password) that relates to the Client and Admin models in a polymorphic relation (morphOne) where they hold other data exclusive to those models.

If no, clients and admin use different routes, then you can differentiate guarding those routes with auth:client or auth:admin depending on their requirements. I have this setup on a project where we had a legacy database structure that our client didn't want to change. It is an e-commerce solution, so the public facing routes requires a member guard, while the admin backend routes require an admin guard. Both with separate login pages. If both member and admin access is needed for the same user, they need to be registered on each table.

When you don't specify a guard for a route Laravel fallback to the default guard to check for the user. It doesn't loop for every guard available. Imagine if you have 10 guards defined, it wouldn't be very performant to make 10 DB queries before failing for every guarded route.

Also Laravel only keeps the auth identifier (generally the id column) value in the session. So without specifying the guard it has no way to tell from each guard you expect that id to come from.

Also how you do differentiate an admin with id = 1 from a client with id = 1? If you have a single user table, two users would not have the same id. You can differentiate clients from admin by adding a role column to the users table, or by using a RBAC (role-based access control) strategy, there are many packages that implements that, and as @jlrdw said, @JeffreyWay covered it so many times here in Laracasts' videos. One package I usually reach for that is this:

https://github.com/spatie/laravel-permission/

If by all means you need to have separated models, can't have a single table and the users from those models will have access to the same routes, you can write a custom User Provider that loops through both models. The official documentation has a section about it:

https://laravel.com/docs/7.x/authentication#adding-custom-user-providers

One tip is to override the getAuthIdentifier method on the Client and Admin models to prefix it with a reference (for example: client:1 and admin:1) so in the provider you can tell which model to query. Also the auth identifier is what is persisted into the session.

You can check the EloquentUserProvider implementation to know how to write your custom one.

Add that custom provider to the default guard and profit.

Activity icon

Replied to How To Login With Different Models In Laravel?

Will both models access the same resources?

For example, both will have access to the same protected routes? (/homepage, etc.)

If yes, I guess you are better using a single model, at least for authentication. You can have a User model that holds auth related stuff (email and password) that relates to the Client and Admin models in a polymorphic relation (morphOne) where they hold other data exclusive to those models.

If no, clients and admin use different routes, then you can differentiate guarding those routes with auth:client or auth:admin depending on their requirements. I have this setup on a project where we had a legacy database structure that our client didn't want to change. It is an e-commerce solution, so the public facing routes requires a member guard, while the admin backend routes require an admin guard. Both with separate login pages. If both member and admin access is needed for the same user, they need to be registered on each table.

When you don't specify a guard for a route Laravel fallback to the default guard to check for the user. It doesn't loop for every guard available. Imagine if you have 10 guards defined, it wouldn't be very performant to make 10 DB queries before failing for every guarded route.

Also Laravel only keeps the auth identifier (generally the id column) value in the session. So without specifying the guard it has no way to tell from each guard you expect that id to come from.

Also how you do differentiate an admin with id = 1 from a client with id = 1? If you have a single user table, two users would not have the same id. You can differentiate clients from admin by adding a role column to the users table, or by using a RBAC (role-based access control) strategy, there are many packages that implements that, and as @jlrdw said, @JeffreyWay covered it so many times here in Laracasts' videos. One package I usually reach for that is this:

https://github.com/spatie/laravel-permission/

If by all means you need to have separated models, can't have a single table and the users from those models will have access to the same routes, you can write a custom User Provider that loops through both models. The official documentation has a section about it:

https://laravel.com/docs/7.x/authentication#adding-custom-user-providers

One tip is to override the getAuthIdentifier method on the Client and Admin models to prefix it with a reference (for example: client:1 and admin:1) so in the provider you can tell which model to query. Also the auth identifier is what is persisted into the session.

You can check the EloquentUserProvider implementation to know how to write your custom one.

Add that custom provider to the default guard and profit.

Mar
22
3 months ago
Activity icon

Replied to HTTP Client Configuration

And I forgot to say on my last response: thanks for the update =)

Activity icon

Replied to HTTP Client Configuration

I looked into the Client source code.

When you call asForm internally it calls that method.

Activity icon

Awarded Best Reply on HTTP Client Configuration

Try this:

$response = Http::withToken('xxx')
    ->bodyFormat('none') // can be anything different of json, form_params or multipart
    ->withOptions(['body' => null]) // set guzzle options
    ->post('https://domain.com/api/account/1/get_stuff', []);
Activity icon

Replied to HTTP Client Configuration

I was thinking about it and maybe you don't need the withOptions(...), only setting bodyFormat(...) to something Guzzle doesn't expect as a body format shoudl suffice.

I tested locally and it should not send the body, but please test against your endpoint to see if it works:

$response = Http::withToken('xxx')
    ->bodyFormat('none')
    ->post('https://domain.com/api/account/1/get_stuff', []);
Activity icon

Awarded Best Reply on Route Model Binding In 7.x

Try this:

Route::resource('posts', 'PostController')->parameter('posts', 'post:slug');

internally resources use the route helpers (get, post, ...) to create the routes. the parameter method tells the resource how to replace the route placeholders

Activity icon

Replied to HTTP Client Configuration

Try this:

$response = Http::withToken('xxx')
    ->bodyFormat('none') // can be anything different of json, form_params or multipart
    ->withOptions(['body' => null]) // set guzzle options
    ->post('https://domain.com/api/account/1/get_stuff', []);
Mar
20
3 months ago
Activity icon

Replied to Visual Math Editor

As the documentation says it manipulates a <textarea> I guess so. Just add a name attribute and a standard <form> would send it without a problem.

If you are fine with user inputting LaTeX syntax directly them you have more options. Check this wikipedia comparison table for many editors:

https://en.wikipedia.org/wiki/Formula_editor

There's a column for platform (check for web) and also a column for open source. Note that not being open source does not mean it is not free, although it is likely that most non-opensource options there are paid/licensed.

Activity icon

Awarded Best Reply on Send The User Back If An Error Thrown

@tudosm take a look at this section on the docs:

https://laravel.com/docs/7.x/errors#the-exception-handler

There you can configure the behavior of your app when some exception is thrown.

Activity icon

Replied to Visual Math Editor

One site I used to solving equations has an online editor:

https://www.fxsolver.com/edit/formula/

so I checked the source to see what they were using:

http://mathdox.org/formulaeditor/

It seems very old and is not updated since 2008 (according to the linked sourceforge site), but it works and is free.

===

EDIT Found this one:

http://www.imatheq.com/corpsite/index.html

Seems more modern, but requires a subscription. Seems you can add to a website as long you have the correct license

Mar
18
3 months ago
Activity icon

Replied to Getting Laravel Sessions

You can use the Crypt facade:

$encryptedValue = Crypt::encrypt($value);

Where value would be your cookie's content

https://laravel.com/docs/7.x/encryption