malhayek

Experience

27,380

0 Best Reply Awards

  • Member Since 2 Years Ago
  • 191 Lessons Completed
  • 22 Favorites

29th October, 2017

malhayek left a reply on What Program Does Jeffrey Way Use To Record The Screencasts? • 3 weeks ago

Thanks all for your help. I ended up using ActivePresenter an awesome free tool https://atomisystems.com/activepresenter/

14th October, 2017

malhayek left a reply on What Program Does Jeffrey Way Use To Record The Screencasts? • 1 month ago

What about Windows users? any ideas

malhayek started a new conversation What Program Does Jeffrey Way Use To Record The Screencasts? • 1 month ago

I wrote a package for Laravel. I have been trying to create a video with audio to show people how to use it. However I have been running into one problem after another.

I tried OBS studio which keep crashing. I tried CamStudio which after I recorded everything it couldn't save the file. Then I tried AVS Video Editor which seems to be good, but after I finish recording the sound is very bad and the text on the video isn't readable.

Since my package is free, I don't really want to spend money on a software that I would use few times.

Any idea on what software Jeff use to record hist videos? any idea on a software that would help me to create this tutorial?

7th October, 2017

malhayek left a reply on What Is The Difference Between "auth" And "auth:api" Middlewares? • 1 month ago

I finally got it to work.

After installing Laravel's passport driver, I added the following middlewear web key in the $middlewareGroups property in the \App\Http\Kernal.php file.

\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,

malhayek left a reply on What Is The Difference Between "auth" And "auth:api" Middlewares? • 1 month ago

I just installed (Laravel passport) https://laravel.com/docs/5.5/passport I thought it may be required. still not sure if it is required or not. Either was that did not solve the problem

malhayek left a reply on What Is The Difference Between "auth" And "auth:api" Middlewares? • 1 month ago

yes I do have all that.. here is how my request looks like

https://image.ibb.co/ndpymG/Screenshot_13.png

malhayek left a reply on What Is The Difference Between "auth" And "auth:api" Middlewares? • 1 month ago

@sutherland I think that is exactly what is happening here.

I tried making the call using JS but I am still getting 401 error

    axios.get('api/route/blah')
            .then(response => {
            console.log(response.data);
        }); 

any idea why?

malhayek started a new conversation What Is The Difference Between "auth" And "auth:api" Middlewares? • 1 month ago

I have an application that I am creating using Laravel 5.5 in which I like to use web routes and some API routes.

I installed Laravel "auth" package using php artisan make:auth https://laravel.com/docs/5.5/authentication

Eveything works great on the web routes. To secure my controller, I add the following code to the controller

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

and the routes will become allowed after a user logs in.

However, when I add routes to the api.php file and add the $this->middleware('auth'); or $this->middleware('auth:api'); the site rejects the access and send the user back to the /home route.

I am wondering why the auth middleware does not recognized that the user is logged in when using the api routes. Also, why auth:api does not also recognize the the user is logged in. Does the api routes expect a different way to login? if so how would I login using an API?

3rd October, 2017

malhayek left a reply on How Do I Define An API Route? • 1 month ago

@ThinkingMan I am using Laravel v5.5.13. I upgraded it from v5.4.

@sutherland I am not using that. As you can see the route is listed in my original question. but that is a good point

malhayek left a reply on How Do I Define An API Route? • 1 month ago

@Snapey I don't actually all of the available routes are grouped with a unique prefix.

@andreasbakir it corresponds to the model id.

2nd October, 2017

malhayek left a reply on How Can I Get The Build In Error Message When Using Form-request? • 1 month ago

I am using the class name in the method.

Here is how my controller looks like when I am using the form-request.

<?php

namespace App\Http\Controllers;

use App\Models\Asset;
use App\Models\AssetCategory;
use App\Http\Controllers\Controller;
use App\Http\Requests\AssetsFormRequest;

class AssetsController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }
    
    /**
     * Display a listing of the assets.
     *
     * @return Illuminate\View\View
     */
    public function index()
    {
        $assets = Asset::with('category')->paginate(25);

        return view('assets.index', compact('assets'));
    }

    /**
     * Show the form for creating a new asset.
     *
     * @return Illuminate\View\View
     */
    public function create()
    {
        $categories = AssetCategory::pluck('name','id')->all();
        
        return view('assets.create', compact('categories'));
    }

    /**
     * Store a new asset in the storage.
     *
     * @param App\Http\Requests\AssetsFormRequest $request
     *
     * @return Illuminate\Http\RedirectResponse | Illuminate\Routing\Redirector
     */
    public function store(AssetsFormRequest $request)
    {
        try {
            
            $data = $request->getData();
            
            Asset::create($data);

            return redirect()->route('assets.asset.index')
                             ->with('success_message', trans('assets.model_was_added'));

        } catch (Exception $exception) {

            return back()->withInput()
                         ->withErrors(['unexpected_error' => trans('assets.unexpected_error')]);
        }
    }

    /**
     * Display the specified asset.
     *
     * @param int $id
     *
     * @return Illuminate\View\View
     */
    public function show($id)
    {
        $asset = Asset::with('category')->findOrFail($id);

        return view('assets.show', compact('asset'));
    }

    /**
     * Show the form for editing the specified asset.
     *
     * @param int $id
     *
     * @return Illuminate\View\View
     */
    public function edit($id)
    {
        $asset = Asset::findOrFail($id);
        $categories = AssetCategory::pluck('name','id')->all();

        return view('assets.edit', compact('asset','categories'));
    }

    /**
     * Update the specified asset in the storage.
     *
     * @param  int $id
     * @param App\Http\Requests\AssetsFormRequest $request
     *
     * @return Illuminate\Http\RedirectResponse | Illuminate\Routing\Redirector
     */
    public function update($id, AssetsFormRequest $request)
    {
        try {
            
            $data = $request->getData();
            
            $asset = Asset::findOrFail($id);
            $asset->update($data);

            return redirect()->route('assets.asset.index')
                             ->with('success_message', trans('assets.model_was_updated'));

        } catch (Exception $exception) {

            return back()->withInput()
                         ->withErrors(['unexpected_error' => trans('assets.unexpected_error')]);
        }        
    }

    /**
     * Remove the specified asset from the storage.
     *
     * @param  int $id
     *
     * @return Illuminate\Http\RedirectResponse | Illuminate\Routing\Redirector
     */
    public function destroy($id)
    {
        try {
            $asset = Asset::findOrFail($id);
            $asset->delete();

            return redirect()->route('assets.asset.index')
                             ->with('success_message', trans('assets.model_was_deleted'));

        } catch (Exception $exception) {

            return back()->withInput()
                         ->withErrors(['unexpected_error' => trans('assets.unexpected_error')]);
        }
    }
    
}

Here is how my controller looks like when I am NOT using form-request

<?php

namespace App\Http\Controllers;

use App\Models\Asset;
use Illuminate\Http\Request;
use App\Models\AssetCategory;
use App\Http\Controllers\Controller;

class AssetsController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }
    
    /**
     * Display a listing of the assets.
     *
     * @return Illuminate\View\View
     */
    public function index()
    {
        $assets = Asset::with('category')->paginate(25);

        return view('assets.index', compact('assets'));
    }

    /**
     * Show the form for creating a new asset.
     *
     * @return Illuminate\View\View
     */
    public function create()
    {
        $categories = AssetCategory::pluck('name','id')->all();
        
        return view('assets.create', compact('categories'));
    }

    /**
     * Store a new asset in the storage.
     *
     * @param Illuminate\Http\Request $request
     *
     * @return Illuminate\Http\RedirectResponse | Illuminate\Routing\Redirector
     */
    public function store(Request $request)
    {
        try {
            
            $data = $this->getData($request);
            
            Asset::create($data);

            return redirect()->route('assets.asset.index')
                             ->with('success_message', trans('assets.model_was_added'));

        } catch (Exception $exception) {

            return back()->withInput()
                         ->withErrors(['unexpected_error' => trans('assets.unexpected_error')]);
        }
    }

    /**
     * Display the specified asset.
     *
     * @param int $id
     *
     * @return Illuminate\View\View
     */
    public function show($id)
    {
        $asset = Asset::with('category')->findOrFail($id);

        return view('assets.show', compact('asset'));
    }

    /**
     * Show the form for editing the specified asset.
     *
     * @param int $id
     *
     * @return Illuminate\View\View
     */
    public function edit($id)
    {
        $asset = Asset::findOrFail($id);
        $categories = AssetCategory::pluck('name','id')->all();

        return view('assets.edit', compact('asset','categories'));
    }

    /**
     * Update the specified asset in the storage.
     *
     * @param  int $id
     * @param Illuminate\Http\Request $request
     *
     * @return Illuminate\Http\RedirectResponse | Illuminate\Routing\Redirector
     */
    public function update($id, Request $request)
    {
        try {
            
            $data = $this->getData($request);
            
            $asset = Asset::findOrFail($id);
            $asset->update($data);

            return redirect()->route('assets.asset.index')
                             ->with('success_message', trans('assets.model_was_updated'));

        } catch (Exception $exception) {

            return back()->withInput()
                         ->withErrors(['unexpected_error' => trans('assets.unexpected_error')]);
        }        
    }

    /**
     * Remove the specified asset from the storage.
     *
     * @param  int $id
     *
     * @return Illuminate\Http\RedirectResponse | Illuminate\Routing\Redirector
     */
    public function destroy($id)
    {
        try {
            $asset = Asset::findOrFail($id);
            $asset->delete();

            return redirect()->route('assets.asset.index')
                             ->with('success_message', trans('assets.model_was_deleted'));

        } catch (Exception $exception) {

            return back()->withInput()
                         ->withErrors(['unexpected_error' => trans('assets.unexpected_error')]);
        }
    }

    
    /**
     * Get the request's data from the request.
     *
     * @param Illuminate\Http\Request\Request $request 
     * @return array
     */
    protected function getData(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|string|min:1|max:255',
            'category_id' => 'required',
            'cost' => 'required|numeric|min:-9999999.999|max:9999999.999',
            'purchased_at' => 'required|date_format:j/n/Y g:i A',
            'notes' => 'nullable|string|min:0|max:1000',
        ]);

        return $data;
    }

}

malhayek left a reply on How Can I Get The Build In Error Message When Using Form-request? • 1 month ago

@JackJones

I am not sure what your asking me. sorry.

Here is how my form-request looks like

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Auth;

class AssetsFormRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required|string|min:1|max:255',
            'category_id' => 'required',
            'cost' => 'required|numeric|min:-9999999.999|max:9999999.999',
            'purchased_at' => 'required|date_format:j/n/Y g:i A',
            'notes' => 'nullable|string|min:0|max:1000',
        ];
    }
    
    /**
     * Get the request's data from the request.
     *
     * 
     * @return array
     */
    public function getData()
    {
        $data = $this->only(['name','category_id','cost','purchased_at','notes']);

        return $data;
    }

}

malhayek started a new conversation How Can I Get The Build In Error Message When Using Form-request? • 1 month ago

I am using Laravel 5.5 in a project.

When I use the $request->validate([....]); directly in the controller to validate an incoming request, everything works fine, and if there is an error, the correct error message will be shown under the field. For example "This field is required".

However, if I use form-request to separate my validation process from the controller, I get this text instead "validation.required". I am aware that I can use the messages() method in my form-request to write custom messages. But if I don't define the messages() method, why doesn't Laravel just display similar message like it would in the controller?

It is possible that I am doing something wrong here.

How can I display the default error messages with form-request

malhayek left a reply on How Do I Define An API Route? • 1 month ago

no because none of my routes in the web.php file start with prefix "api"

malhayek left a reply on How Do I Define An API Route? • 1 month ago

@Snapey I thought the idea of having multiple route file is that you don't have to add a prefix.

In fact, when looking at the mapApiRoutes() method in the RouteServiceProvider you'll notice that the framework automatically prefix all the routes with the word "api"

https://github.com/laravel/laravel/blob/master/app/Providers/RouteServiceProvider.php

malhayek left a reply on Is There A Way To Generate Url From Route Name With Javascript? • 1 month ago

Thank you. That will work!

1st October, 2017

malhayek started a new conversation Is There A Way To Generate Url From Route Name With Javascript? • 1 month ago

I am aware that route naming is something that is handled at the server side not the client. However, I hate the idea of having to hard code my urls is my JS file which defeats the purpose of using route naming.

Sine I am using mixer/webpack, I am hoping there is some kind of helper that will fetch and generate the url by giving it the route name.

I am thinking of something like this

$.ajax({
        url: resolve_url('my_laravel_route_name'),
        method: 'POST',
        data: {},
        dataType: 'JSON'
    });

instead of hard coding the url

$.ajax({
        url: 'some_url/for/my/api',
        method: 'POST',
        data: {},
        dataType: 'JSON'
    });

Is there some something like this?

malhayek started a new conversation How Do I Define An API Route? • 1 month ago

I never used Laravel to create API application. This time I have an application that need web routes and some API route.

For my API route, I added the following route to my /routes/api.php file

Route::get('getinfo/{id}', '[email protected]') ->name('some_name') ->where('id', '[0-9]+');

However, when I go to /myapp.dev/api/getinfo/1 I get redirected to /home url.

What else that is different that I have to do to get the api routes to work?

28th September, 2017

malhayek left a reply on How Can I Change A Char Column Using Migrations? • 1 month ago

@JackJones you are looking at an old documentation. Look at doc v5.5 https://laravel.com/docs/5.5/migrations#column-modifiers

27th September, 2017

malhayek left a reply on How Can I Change A Char Column Using Migrations? • 1 month ago

So using built in setup, this isn’t possible without having to drop and add column?

25th September, 2017

malhayek started a new conversation How Can I Change A Char Column Using Migrations? • 1 month ago

Accordi to Laravel's documentation, the change() method can not be used to change the following column types

'char', 'double', 'enum', 'mediumInteger', 'timestamp', 'tinyInteger', 'ipAddress', 'json',
'jsonb', 'macAddress', 'mediumIncrements', 'morphs', 'nullableMorphs', 'nullableTimestamps', 'softDeletes', 'timeTz', 'timestampTz', 'timestamps', 'timestampsTz', 'unsignedMediumInteger', 'unsignedTinyInteger', 'uuid'

So if I want to increase the size of a char field, or if I want to change the type of the field from char to string, how would I do that using migrations?

22nd September, 2017

malhayek started a new conversation What Is The Right Way To Check If A Migration Is Already Ran? • 2 months ago

Laravel offers a php artisan migrate:status command that lists all migration and weather or it the migration run. However, I am intersected in checking if a giving migration name has run or not? In another words, I want to be able to answer "has the migration name 2017_09_17_230130_create_assets_table" has run or not at run time?

Also, is it possible to group the migrations into folders inside the database/migrations folder??

15th September, 2017

malhayek left a reply on Is There A Way To Get A List Of The Migrated Classes After Migrations Takes Place? • 2 months ago

I actually want to do that inside of a package that I wrote.

I can't modify these classes which is why I need to listen to an event

malhayek left a reply on Is There A Way To Get A List Of The Migrated Classes After Migrations Takes Place? • 2 months ago

@Snapey I want to know each time the up() or down() methods in a migration class. So I am asking about when the code interact with the database.

I have some logic that I like to run each time an outstanding migration is migrated or rolled back.

malhayek started a new conversation Is There A Way To Get A List Of The Migrated Classes After Migrations Takes Place? • 2 months ago

Hi,

Is there a way do get a list of the migrations class names when the php artisan migrate command is called, or when migrate:rollback is called?

I am hoping that Laravel fires an event upon the execution of these commands. What event can I listen for to know the change names?

13th September, 2017

malhayek left a reply on How Can I Check If The App Is Using The ConvertEmptyStringsToNull Middleware? • 2 months ago

@spodlogar That is exactly what I need :)

Does the make() method creates a new instance each time or does it create a new one if one does not already exists?

Also, is make() behaves the same on Laravel 5.1+?

malhayek left a reply on How Can I Check If The App Is Using The ConvertEmptyStringsToNull Middleware? • 2 months ago

@spodlogar, I know that :) but in order for me to do a real-time "when the command is called" check to see if the middleware is registred, I would need to create a instances of the Kernel class then possible call the hasMiddleware method to get the answer.

My question is how can I create an instance of this class

malhayek left a reply on How Can I Check If The App Is Using The ConvertEmptyStringsToNull Middleware? • 2 months ago

@jlrdw I am not following you. What do you mean?

malhayek started a new conversation How Can I Check If The App Is Using The ConvertEmptyStringsToNull Middleware? • 2 months ago

I am writing a Laravel console-command. In the command, I need to know if the ConvertEmptyStringsToNull is a registered middlewear or not.

When I looked at Illuminate\Foundation\Http\Kernel (https://laravel.com/api/5.1/Illuminate/Foundation/Http/Kernel.html) I can see that it has a method called hasMiddleware public method that should give me what I need.

However, I am not sure what is the correct way to create a new of the App\Http\Kernel which expends the Illuminate\Foundation\Http\Kernel class.

My command class extends the Illuminate\Console\Command like this

use Illuminate\Console\Command;

class CreateControllerCommand extends Command 
{
    public function handle()
    {
        $router = new \Illuminate\Routing\Router(); // this is not working!
        $kernel = new \App\Http\Kernel($this->getLaravel(), $router);  // $this->getLaravel() is a method that the Illuminate\Console\Command has which return the instance of the application
    }
}

Is there a better way to check if the app has the ConvertEmptyStringsToNull middleware beside creating a new instance of the Kernel class? Is there a way to access the Kernel class without creating a new instance? If not, what is the proper way to create a new instance of the Kernel class?

9th July, 2017

malhayek left a reply on How Can I Include Bootstrap-datetimepicker In My Mix Setup? • 4 months ago

Thanks for the tip about the available download for node.js.

But, does that means I can't include a package that does not have node.js installer?

Also, how can I include the package's css file into my own app.sass class? how do I include it?

8th July, 2017

malhayek started a new conversation How Can I Include Bootstrap-datetimepicker In My Mix Setup? • 4 months ago

I need to include bootstrap-datetimepicker into my Mix setup. https://github.com/Eonasdan/bootstrap-datetimepicker

The bootstrap-datetimepicker package does not offer Node.js installer. How can I include it in my project?

Here is what I tried, I added a folder resources/assets/vendors and manually download the https://github.com/Eonasdan/bootstrap-datetimepicker in to it.

Then in my resources/assets/app.sass the following line

@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap";

But i am getting the following error when compiling the assets using npm run watch

Module build failed: ModuleNotFoundError: Module not found: Error: Can't resolve
 './resources/assets/vendors/bootstrap-datetimepicker-4.17.47/build/css/bootstra
p-datetimepicker.css' in 'resources\assets\sass' at factoryCallback (node_modules\webpack\lib\Compilation.js:260:39)

28th June, 2017

malhayek left a reply on How Can I Set Default Value With Form::selectRange And Form::selectMonth? • 4 months ago

How would Form::hidden allows me to set the default value for Form::selectMonth or Form::selectRange?

27th June, 2017

malhayek started a new conversation How Can I Set Default Value With Form::selectRange And Form::selectMonth? • 4 months ago

I am trying to use Laravel-Collective (https://laravel.com/docs/5.4/authentication#protecting-routes)

When using checkbox I am doing this to check if there is an older value then set the it otherwise use the default. Then I am using isset($biography->colors) to know if this is an edit request or not. if isset($biography->colors) true I'll set its value.

        <label for="colors_white" class="checkbox-inline">
            {!! Form::checkbox('colors[]', 'White',  (in_array('White', old('colors', isset($biography->colors) ? $biography->colors : ['White','Red'])) ? true : null) , ['id' => 'colors_white', 'class' => 'required' ]) !!}
            White
        </label>

How can I do the same thing with Form::selectRange and Form::selectMonth?

25th June, 2017

malhayek started a new conversation What Validation Rule So I Use To Validate The Length Of A String? • 4 months ago

I need to add a validation rule that restrict a string to be between 3 and 255 characters in length. This is a string not just a number.

I tried to use

required|digits_between:3,255

But the above is returning an error when i pass this string "This is a string test"

How can I validation the length of string?

19th June, 2017

malhayek left a reply on How To Redirect The User Back To The View With Error When The Controller Return Exception? • 5 months ago

@aydinbulut I know how to fix the error. In fact, I purposely generated the error by setting my $data variable to [] after the request was validated so I can write code to capture the errors.

All I want to do is go back to the same form the user was one. Then I want to show them a user friendly error. I don't really want to add global custom pages.

malhayek left a reply on How To Redirect The User Back To The View With Error When The Controller Return Exception? • 5 months ago

@Swapnil I think the main question here is how to trap these error so I can return a user friendly error.

flash does similar idea to `with('success_message','Message......')

my main problem is that the app still shows a full trace stack even when I used try/catch

malhayek started a new conversation How To Redirect The User Back To The View With Error When The Controller Return Exception? • 5 months ago

In some unexpected cases my controller would return exception. Instead of showing the user error trace, I want to show them a user friendly error instead. (query timeout, duplicate record or something at the database level)

Here is my method

    public function store(AssetCategoryFormRequest $request)
    {
        $data = $request->getData();
        
        AssetCategory::create($data);
        Session::flash('success_message', 'AssetCategory was added!');

        return redirect()->route('asset_categories.assetcategory.index');
    }

I am guessing one way would be by using try/catch block

    public function store(AssetCategoryFormRequest $request)
    {
        try {
            $data = $request->getData();
            
            AssetCategory::create($data);
            Session::flash('success_message', 'AssetCategory was added!');

            return redirect()->route('asset_categories.assetcategory.index');
        } catch(QueryException $e) {
            // But how to return to the same view and still pass an error message
            // I don't want to loose my request data also.


        }
    }

Is there a better way that using try/catch or is this the best way to go? How can I return the user back to the same view along with the request data and an error message?

26th May, 2017

malhayek started a new conversation What Is The Best Practice For Designing Site With Laravel? • 5 months ago

I need to write a system on the top of Laravel 5.4. This system needs to handle 2 languages.

I understand that Laravel has a built in handling for diffident locales. But what about routes? What is the best practice for such a system?

Do I prefix the my routes with the language key? How do I do that?

25th March, 2017

malhayek left a reply on How Can I Submit Code Improvement Of Laravel To Taylor? • 7 months ago

@clay So I forked the laravel/framework project. I made the changes and a commited/pushed my changed. My new code is now on my forked project on git hub.

Now, I want to submit my change for Taylor hoping he'll merge my code with the master branch.

I went to the original project (https://github.com/laravel/framework) and clicked on "New Pull Request" which sent me to this link https://github.com/laravel/framework/compare?expand=1

I am confused on which branch/tag to I pick and also how to I tell it to take my code and send it?

21st March, 2017

malhayek started a new conversation How Can I Call A Listener Outside The Score Of A Database Transaction? • 8 months ago

I have setup event and few listeners in my app which works well.

In my controller, I run all my code inside the score of a transaction. However, there is one listener that executes a query which I want it to be outside of the transaction scope. So it should be executed by itself and should not impact the transaction.

Is this something possible? How?

19th March, 2017

malhayek started a new conversation How Can I Submit Code Improvement Of Laravel To Taylor? • 8 months ago

I have a feature that I wish to add to Laravel which I think will help the community a lot.

I never contributed to someone else project and wish to do that this time.

How can I pull the development version of Laravel 5.5, add my code then send the change to Taylor hoping he will consider adopting this feature?

I am not very good with Git, so I would appreciate some help with the commands.

malhayek left a reply on What Is The Best Way To Handle The Datetime In Laravel? • 8 months ago

Thank you. What I ended up doing is creating a property that will auto manage this process for me. this is what I have done

in the config\app.php config file I added the following two lines.

    'fallback_in_format' => 'Y-m-d H:i:s',
    'fallback_out_format' => 'd/m/Y H:i A',

Then I created a new base class for my models like the following

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class BaseModel extends Model
{
    protected $fixedFormattedFields = null;

    /**
     * Get a plain attribute (not a relationship).
     *
     * @param  string  $key
     * @return mixed
     */
    public function getAttributeValue($key)
    {
        if( ($field = $this->getFieldToFormat($key)) != null)
        {
            return date($field['out_format'], strtotime($this->getAttributeFromArray($key)));
        }

        return parent::getAttributeValue($key);
    }

    /**
     * Set a given attribute on the model.
     *
     * @param  string  $key
     * @param  mixed  $value
     * @return $this
     */
    public function setAttribute($key, $value)
    {
        if( ($field = $this->getFieldToFormat($key)) != null)
        {
            $this->attributes[$key] = date($field['in_format'], strtotime($value));

            return $this;
        }

        return parent::setAttribute($key, $value);
    }
    
    /**
     * Get the format property for a given attribute on the model.
     *
     * @param  string  $key
     * @return mix (null|array)
     */
    protected function getFieldToFormat($key)
    {
        foreach($this->getFixedFormattedFields() as $field)
        {
            if($field['key'] == $key)
            {
                return $field;
            }
        }

        return null;
    }

    /**
     * Gets a fields to auto format.
     *
     * @return array
     */
    protected function getFixedFormattedFields()
    {
        if( is_null($this->fixedFormattedFields))
        {
            $this->fixedFormattedFields = [];

            if( property_exists($this, 'formattedDates') && is_array($this->formattedDates))
            {
                foreach($this->formattedDates as $field)
                {
                    if(!is_array($field))
                    {
                        $this->fixedFormattedFields[] = $this->getFixedFormattedField($field);
                        continue;
                    }

                    if(isset($field['key']))
                    {
                        $inFormat = isset($field['in_format']) ? $field['in_format'] : null;
                        $outFormat = isset($field['out_format']) ? $field['out_format'] : null;

                        $this->fixedFormattedFields[] = $this->getFixedFormattedField($field['key'], $inFormat, $outFormat);
                    }
                }
            }
        }

        return $this->fixedFormattedFields;
    }

    /**
     * Get get a standard format for the fields to auto format.
     *
     * @param  string  $key
     * @param  string $inFormat
     * @param  string $outFormat
     * @return array
     */
    protected function getFixedFormattedField($key, $inFormat = null, $outFormat = null)
    {
        return 
        [   
            'key' => $key,
            'in_format' => is_null($inFormat) ? config('app.fallback_in_format') : $inFormat,
            'out_format' => is_null($outFormat) ? config('app.fallback_out_format') : $outFormat
        ];
    }
}

Then in my model I do the following

<?php

namespace App\Models;

use App\Models\BaseModel;

class Expense extends BaseModel
{
    /**
     * Datetime attributes that should be auto manages
     *
     * @var array
     */
    protected $formattedDates = [
                                    [
                                     'key'        => 'paid_at',
                                     'in_format'  => 'Y-m-d H:i:s',
                                     'out_format' => 'd/m/Y H:i A'
                                    ],
                                    'starts_at',
                                    'ends_at'
                                ];

}

As you can see, now all I need to do is define the fields in the $formattedDates property. I can also specify the a different format for each property if I wish.

I hope this helps someone out there.

malhayek left a reply on Where Does Laravel Magically Handle The Mutator And Accessors? • 8 months ago

Thank you very much

malhayek left a reply on What Is The Best Way To Handle The Datetime In Laravel? • 8 months ago

I apologize, I am not following you. An example will be greatly appreciated.

malhayek started a new conversation Where Does Laravel Magically Handle The Mutator And Accessors? • 8 months ago

So Laravel uses reflection to look for an accessor or mutator method to apply custom logic when accessing a field or before saving the field in the database.

But, in what file in its code does it do this?

My guess is be by utilizing the php's own magic method __get() and __set(). I reviewed the Illuminate\Database\Eloquent class but, I don't see how in there Taylor is checking for the set*Attribute and get*Attribute pattern.

Where can I find the code that handles this?

malhayek left a reply on What Is The Best Way To Handle The Datetime In Laravel? • 8 months ago

@jlrdw I am trying to find a better way to handle the process of converting string to datetime and datetime to string on accessing or mutating the data without having to write 2 methods per field.

malhayek left a reply on What Is The Best Way To Handle The Datetime In Laravel? • 8 months ago

@jlrdw that link explains how to create helper methods. Are you saying to create a a global function two function to handle the conversion but still create a getter and setter for each field in each model?


function dateTimeToString($value)
{
    return date('d/m/Y  H:i A', strtotime($value));
}

function stringToDateTime($value)
{
    return date('Y-m-d H:i:s', strtotime($value));
}

Than my model will look like this

    /**
     * Mutate the paid_at to a valid date time
     *
     * @param  string  $value
     * @return void
     */
    public function setPaidAtAttribute($value)
    {
        $this->attributes['paid_at'] = stringToDateTime($value);
    }


    /**
     * Get the paid_at value.
     * @param  string  $value
     * @return string
     */
    public function getPaidAtAttribute($value)
    {
        return dateTimeToString($value);
    }

malhayek left a reply on What Is The Best Way To Handle The Datetime In Laravel? • 8 months ago

Corrent. If I understand you correctly, your saying to create a global getter and setter. this mean, I would need to hook into each model and for each field of the type datetime, apply a getter and a setter.

malhayek left a reply on What Is The Best Way To Handle The Datetime In Laravel? • 8 months ago

Are you saying that getter/setter is the best way to handle this?

How would I know the field type? How would create a global helper?

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.