malhayek

Experience

28,600

0 Best Reply Awards

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

27th January, 2018

malhayek left a reply on How To Get The URI Resource From A Giving Route Name? • 3 months ago

@skliche Thank you for that. That got me very close. I was able to get the job done using the following

Route::getRoutes()->getByName(''api.assets.v2.asset.show'')->uri()

malhayek left a reply on How To Get The URI Resource From A Giving Route Name? • 3 months ago

@burlresearch I actually want to get the following value as-is "api/assets/v2/show/{asset}" meaning, I don't want it resolved. I basically want to show that value on my API documentation.

21st January, 2018

malhayek started a new conversation How To Get The URI Resource From A Giving Route Name? • 4 months ago

I have a route named api.assets.v2.asset.show which is mapped to the following URI api/assets/v2/show/{asset}. I can see that info available in the php artisan route:list.

I am looking for a way to obtain the api/assets/v2/show/{asset} string when api.assets.v2.asset.show is giving.

In the ResourceRegistrar.php file https://github.com/drbyte/laravel-framework/blob/master/src/Illuminate/Routing/ResourceRegistrar.php#L123-L143 I can see a method called getResourceUri() which seems to be what I am looking for.

But, how can I call this method from inside my view?

I tried adding the following to my blade view {{ Route::getResourceUri('api.assets.v2.asset.show') }} But that is giving me the following error

Attribute [getResourceUri] does not exist.

Any idea on how to get the URI resource from a giving route name?

15th January, 2018

malhayek left a reply on Is There A Best Practices To Document An API For Public? • 4 months ago

@burlresearch thank you for your feedback again. artisan route:list will give you most of that info if your the developer but an outside person who is looking to integrate their system won't have access to that.

Regarding our 4 bullet, In a typical Laravel based API, how would one establish connection? I mean how would one trying to interact with the API generate a token? Does the token change ofter like the csrf token or is it like a session id?

Thank you

14th January, 2018

malhayek left a reply on Is There A Best Practices To Document An API For Public? • 4 months ago

@jbloomstrom @burlresearch Thank you for the input and help with this.

I created a small dummy api documentation page which can be found here https://jsfiddle.net/DTcHh/41786/

Can you please share with me your thought on this style? Is it missing anything or is it complete? Does it do a good job explaining everything?

Thank you

12th January, 2018

malhayek started a new conversation Is There A Best Practices To Document An API For Public? • 4 months ago

I have an API that is written on a top of Laravel 5.5. I need to write some sort of documentation for it so people know how to use it.

Is there is a best practice document that I can use as a guide to help me writing the document?

Is there an API example of a Laravel project with document that I can look at? Or is there a standard documentation template that the community use with Laravel based APIs?

6th January, 2018

malhayek left a reply on How To Check If Validation Fail With Form-request? • 4 months ago

it's there.

malhayek left a reply on How To Check If Validation Fail With Form-request? • 4 months ago

When I add the following method to my formRequest, I get an error

    /**
     * Handle a failed validation attempt.
     *
     * @param  \Illuminate\Contracts\Validation\Validator  $validator
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function failedValidation(Validator $validator)
    {
           dd('test');
    }

Here is the error

ReflectionException in RouteSignatureParameters.php line 25: 
Class App\Http\Requests\AssetsFormRequest does not exist

But when I don't add it, I get redirected to the main page when the validation fails

And yes, the AssetsFormRequest class exists.

I tried to do composer dump-autoload

Any idea why this isn't working?

5th January, 2018

malhayek started a new conversation How To Check If Validation Fail With Form-request? • 4 months ago

I am trying to write an API CRUD. When the validation fail, instead of redirecting the user to the home page, O want to return json based response with the errors.

I am able to do that using the following code

    public function store(Request $request)
    {
        try {
            $validator = $this->getValidator($request);

            if ($validator->fails()) {
                return $this->errorResponse($validator->errors()->all());
            }
            
            $asset = Asset::create($request->all());

            return $this->successResponse(
                'Asset was successfully added!',
                $this->transform($asset)
            );
        } catch (Exception $exception) {
            return $this->errorResponse('Unexpected error occurred while trying to process your request!');
        }
    }

    /**
     * Gets a new validator instance with the defined rules.
     *
     * @param Illuminate\Http\Request $request
     *
     * @return Illuminate\Support\Facades\Validator
     */
    protected function getValidator(Request $request)
    {
        $rules = [
            'name' => 'required|string|min:1|max:255',
            'category_id' => 'required',
            'cost' => 'required|numeric|min:-9999999.999|max:9999999.999',
            'purchased_at' => 'nullable|string|min:0|max:255',
            'notes' => 'nullable|string|min:0|max:1000',
            'picture' => 'nullable|string|min:0|max:255',
        ];

        return Validator::make($request->all(), $rules);
    }

Now, I like to extract some of my code into a form-request. I like to change my code to something like this. As you can probably tell that $request->fails() and $request->errors()->all() is not going to work. But how can I check if the request failed and then how can I get the errors out of the form-request?

    public function store(AssetFormRequest $request)
    {
        try {
            if ($request->fails()) {
                return $this->errorResponse($request->errors()->all());
            }            
            $asset = Asset::create($request->all());

            return $this->successResponse(
                'Asset was successfully added!',
                $this->transform($asset)
            );
        } catch (Exception $exception) {
            return $this->errorResponse('Unexpected error occurred while trying to process your request!');
        }
    }

31st December, 2017

malhayek started a new conversation How To Get The Paganation Info In Array • 4 months ago

I need to display the pagination info only as array. I tried to use toArray() method, but it include the data which I don't really need. So I tried to remove the data key from the array but I don't like the fact that i have to cast the model to array then remove it. I am hoping there is an easier way to do this without having to cast the data then removing it.

Here is my code.

    public function index()
    {
        $posts = Post::paginate(25);

        $data = [];

        foreach($posts as $post)
        {
            $data[] = $post->getApiData();
        }

        $paginate = $posts->toArray();
        unset($paginate['data']);

        return response()->json([
            'success' => true,
            'message' => 'Posts retrieved successfully',
            'data' => $data,
            'paginate' => $paginate
        ]);
    }

26th November, 2017

malhayek left a reply on How To Add "browser_components" Path To The Webpack Config? • 5 months ago

I was able to get around the warning by changing my code to the following

var modules = mix.resolve.modules;

    modules.push(path.resolve(__dirname, 'bower_components'));

mix.webpackConfig({
    resolve: {
        modules: modules
    }
});

However, I am still getting the following error in the browser's console.

Error: Cannot find module "lodash"

25th November, 2017

malhayek started a new conversation How To Add "browser_components" Path To The Webpack Config? • 5 months ago

I need to include the "bower_components" directory in the webpack config so I can use packages that are installed via bower into my project.

So I used mix.webpackConfig to add the new path like so

mix.webpackConfig({
    resolve: {
        modules: [
            path.resolve(__dirname, 'node_modules')
            path.resolve(__dirname, 'bower_components')
        ]
    }
});

However, when I compile my resources using npm run watch I get the following warnings

WARNING in ./resources/assets/js/bootstrap.js
Module not found: Error: Can't resolve 'bootstrap-sass' in 'C:\xampp\htdocs\Booker\resources\assets\js'
 @ ./resources/assets/js/bootstrap.js 13:2-27
 @ ./resources/assets/js/app.js
 @ multi ./resources/assets/js/app.js ./resources/assets/sass/app.scss

WARNING in ./resources/assets/js/bootstrap.js
Module not found: Error: Can't resolve 'jquery' in 'C:\xampp\htdocs\Booker\resources\assets\js'
 @ ./resources/assets/js/bootstrap.js 11:29-46
 @ ./resources/assets/js/app.js
 @ multi ./resources/assets/js/app.js ./resources/assets/sass/app.scss

Then in the browser's client I get the following error Error: Cannot find module "lodash"

How can I correctly include the bower_components path info my webpack setup so I can use the packages that are installed using bower?

29th October, 2017

malhayek left a reply on What Program Does Jeffrey Way Use To Record The Screencasts? • 6 months 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? • 7 months ago

What about Windows users? any ideas

malhayek started a new conversation What Program Does Jeffrey Way Use To Record The Screencasts? • 7 months 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? • 7 months 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? • 7 months 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? • 7 months 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? • 7 months 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? • 7 months 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? • 7 months 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? • 7 months 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? • 7 months 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? • 7 months 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? • 7 months 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? • 7 months 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? • 7 months 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? • 7 months 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? • 7 months 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? • 7 months 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? • 7 months 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? • 7 months 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? • 7 months 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? • 8 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? • 8 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? • 8 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? • 8 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? • 8 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? • 8 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? • 8 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? • 8 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? • 10 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? • 10 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? • 10 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? • 10 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? • 10 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? • 11 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? • 11 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? • 11 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?

Edit Your Profile
Update

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