malhayek

malhayek

Member Since 3 Years Ago

Experience Points 28,980
Experience
Level
Lessons Completed 200
Lessons
Completed
Best Reply Awards 0
Best Answer
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

17 Sep
1 month ago

malhayek left a reply on How To Pass An Optional Parameter To A Route?

@Cronix thanks for explaining it.

I am not sure why the router does not deal with the query-parameter. I feel that it should be. The router should scan the form-data with in the request and also the query parameter and set the variable accordingly.

It is what it is I guess

malhayek started a new conversation How To Pass An Optional Parameter To A Route?

I have the following controller

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Customer;

class CustomersController extends Controller
{
    /**
     * Display a listing of the customers.
     *
     * @return Illuminate\View\View
     */
    public function index($term = null)
    {
        $customers = Customer::search($term)->paginate(25);

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

Then I have the following route.

Route::group([
    'prefix' => 'customers',
], function () {
    Route::get('/{term?}', '[email protected]')
        ->name('customers.customer.index');

    // other routes are removed from simplicity
});

I am expecting that the above would scan the the form-date add/or the URL parameters and sets the matching parameter in the action method. In other words, I am expecting that the $term variable would get set if I go to the following URL http://app.test/customers?term=term

however, when I go to the following url http://app.test/customers?term=term the $term variable would always be set to NULL

How can I correctly pass this optional param to the action method?

15 Sep
1 month ago

malhayek left a reply on Is It Possible To Use API Resource To Return JSONP?

I added the following method to my TopicResouce class

    /**
     * Customize the response for a request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Http\JsonResponse  $response
     * @return void
     */
    public function withResponse($request, $response)
    {
        $response->withCallback($request->input('callback'))
            ->header('Content-Type', 'application/javascript');
    }

The header changed but I am not sure about the callback

malhayek started a new conversation Is It Possible To Use API Resource To Return JSONP?

I am trying to use jquery.ui autocomplete https://jqueryui.com/autocomplete/#remote in my Laravel 5.7 project.

It seems that the jquery.ui.autocomplete package expect jsonp not standard json. I have been creating a new ApiResource for all of my resources, so I would like to also use Api Resource to response to the autocomplete request.

Is there a way change the response type when using Api Resources?

Here is home my controller looks like

class DriversController extends Controller
{
    /**
     * Display the specified reservation.
     *
     * @param int $vehicleId
     *
     * @return App\Resources\VehicleResources
     */
    public function find($term)
    {
        $searchFor = trim($trem, " \t\n\r
class TopicResource extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            // return something cool
        ];
    }

    /**
     * Returns other attributes to the request
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function with($request)
    {
        return [
            'status' => 'success',
        ];
    }
}
\x0B%"); $topics = Topic::where('fullname', 'like', $searchFor . '%')->get(); return new TopicResource($topics); } }

Here is my resource

LARACASTS_SNIPPET_PLACEHOLDER
08 Sep
2 months ago

malhayek left a reply on Form-request Class Does Not Exist!

@Cronix found the issues. the form request had a syntax error which for some reason was causing everything to error. The line 'payments' => 'required|array' is missing a comma at the end

malhayek left a reply on Form-request Class Does Not Exist!

@Cronix I am running into the same issues with all of my form-requests. It seems that the whole folder is ignored and it not autoloaded.

malhayek left a reply on Form-request Class Does Not Exist!

@Cronix same outcome unfortunately. I have not used PHP is a while and I just remembered why I moved on to a strongly typed language :)

I did just upgraded my project from Laravel 5.5 to 5.6 and then to 5.7, not sure if there is something I missed. but I double checked the upgrade notes and I think I got everything in place

malhayek left a reply on Form-request Class Does Not Exist!

I even tried to recreate the form-request using php artisan make:request ReservationPickupsFormRequest

malhayek left a reply on Form-request Class Does Not Exist!

@Cronix here is the screenshot of the error

https://ibb.co/fUbtfU

malhayek left a reply on Form-request Class Does Not Exist!

@adamprickett @MortenS sorry that was my mistake. I posted the wrong form-request. updating the question now

malhayek started a new conversation Form-request Class Does Not Exist!

I am trying to use a form-request class to validate an incoming update request. But every time I post data to the process method, I get the

Reflection Error: Class App\Http\Requests\ReservationPickupsFormRequest does not exist

I am not sure what could be causing this issue.

I have executed composer dumpautoload command and it did not help.

I created the following routes

Route::group([
    'prefix' => 'reservation_pickups',
], function () {
    Route::get('/', '[email protected]')
        ->name('reservation_pickups.reservation_pickup.index');
    Route::get('/pickup/{id}', '[email protected]')
        ->name('reservation_pickups.reservation_pickup.pickup')
        ->where('id', '[0-9]+');
    Route::post('/process/{id}', '[email protected]')
        ->name('reservation_pickups.reservation_pickup.process');
});

My form-request class looks like this

<?php

namespace App\Http\Requests;

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

class CreditPaymentsFormRequest 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()
    {
        $rules = [
            'credit_id' => 'required',
            'paid_at' => 'required|date_format:j/n/Y g:i A',
            'paid_amount' => 'required|numeric|min:-9999999.999|max:9999999.999',
        ];

        return $rules;
    }

    /**
     * Get the request's data from the request.
     *
     *
     * @return array
     */
    public function getData()
    {
        $data = $this->only(['credit_id', 'paid_at', 'paid_amount']);

        return $data;
    }
}

Finally my controller looks like this

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Http\Requests\ReservationPickupsFormRequest;
use App\Models\Reservation;
use Carbon\Carbon;

class ReservationPickupsController extends Controller
{
    /**
     * Display a listing of the reservations.
     *
     * @return Illuminate\View\View
     */
    public function index()
    {
        $reservations = $this->getPickupQuery()->paginate(25);

        return view('reservation_pickups.index', compact('reservations'));
    }

    /**
     * Show the form for creating a new reservation.
     *
     * @return Illuminate\View\View
     */
    public function pickup($id)
    {
        $reservation = $this->getPickupQuery()->findOrFail($id);

        return view('reservation_pickups.pickup', compact('reservation'));
    }

    /**
     * Process the pickup of the reservation.
     *
     * @param int $id
     * @param App\Http\Requests\ReservationPickupsFormRequest $request
     *
     * @return Illuminate\View\View
     */
    public function process(ReservationPickupsFormRequest $request)
    {
        dd('request', $request->getData());

        $reservation = $this->getPickupQuery()->findOrFail($id);

        // process the update
    }

    /**
     * Get the base query builder for the pickable reservations
     *
     * @return Illuminate\Database\Eloquent\Builder builder
     **/
    private function getPickupQuery()
    {
        $query = Reservation::with('primaryDriver', 'vehicle', 'additionalDrivers')
            ->where('status', 'scheduled')
            ->where('reserved_from', '<=', Carbon::now()->endOfDay());

        return $query;
    }
}
07 Sep
2 months ago

malhayek left a reply on How Can I Get Users Through A Relation Table Using Eloquent?

I had a typo. The following worked

    public function users()
    {
        return $this->hasManyThrough('App\Models\User', 'App\Models\ReservationToUser');
    }

Thank you all

malhayek left a reply on How Can I Get Users Through A Relation Table Using Eloquent?

@Cronix in my case I don't want the data in between. my structure is like this reservation >> relations >> users. I don't really case about the relations all I need in the final model "the users" the relations table should only be used to identify the users. But this isn't working

return $this->hasManyThrough('App\Models\User', 'App\Models\ReservationToUser');`

malhayek left a reply on How Can I Get Users Through A Relation Table Using Eloquent?

@tykus can you please help me writing the relation. the following is throwing a SQL exception

    public function users()
    {
        return $this->hasManyThrough('App\Models\User', 'App\Models\ReservationToUser');
    }

malhayek started a new conversation How Can I Get Users Through A Relation Table Using Eloquent?

I have the following tables

Reservations TableName : reservation ModelName: App\Models\Reservation Columns, id, and few irreverent columns

Relations TableName : reservation_to_users ModelName: App\Models\ReservationToUser Columns, id, user_id, reservation_id

Users TableName : users ModelName: App\Models\User Columns, id, and few irreverent columns

On the App\Models\Reservation model, I want to be access all users that are associated with the current reservation.

What relation type do I use MorphToMany or hasManyThrough?

I tried using

hasManyThrough('App\Models\User', 'users')

but that is throwing SQL errors

What is the right way to access the users from the reservation?

05 Aug
3 months ago

malhayek left a reply on How To Access Uploaded Files?

@Snapey That indeed was the problem. Thank you!

I need to store 'uploads/filename.extension' into the database. I am using the store method on the file to move the file like so

$uplodedFile = $file->store('public/uploads', config('filesystems.default'));

However, the variable $uplodedFile returns public/uploads/filename.extension. Is there a different method to use that store so I can easily return /uploads/filename.extension instead of public/uploads/filename.extension

The problem with storing public/uploads/filename.extension in the database is that the method asset() will render the url to this domain.com/public/uploads/filename.extension instead of domain.com/storage/uploads/filename.extension

malhayek started a new conversation How To Access Uploaded Files?

I am trying to allow my users to upload files.

I am using the following code to save the uplaoded file

$file->store('uploads', config('filesystems.default'))

The files are getting uploaded to storage/app/uploads as expected.

But I am unable to access the uploaded files.

In my views I am using the following to show the URL for the attachment

{{ asset('storage/uploads/d4PH5XJ1wU165nN5EQXzDcxBCvgmAn5p1uRGIrCJ.txt') }}

the above code returns the following

http://domain.com/storage/uploads/d4PH5XJ1wU165nN5EQXzDcxBCvgmAn5p1uRGIrCJ.txt

I ran the php artisan storage:link command which created the symbolic link. However, that link returns the following error

NotFoundHttpException in RouteCollection.php line 179:

How can I correctly expose the uploaded file to the public?

27 Jan
9 months ago

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

@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?

@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.

21 Jan
9 months ago

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

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?

15 Jan
9 months ago

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

@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

14 Jan
10 months ago

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

@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

12 Jan
10 months ago

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

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?

06 Jan
10 months ago

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

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?

05 Jan
10 months ago

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

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!');
        }
    }

31 Dec
10 months ago

malhayek started a new conversation How To Get The Paganation Info In Array

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
        ]);
    }
26 Nov
11 months ago

malhayek left a reply on How To Add "browser_components" Path To The Webpack Config?

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"
25 Nov
11 months ago

malhayek started a new conversation How To Add "browser_components" Path To The Webpack Config?

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?

29 Oct
1 year ago

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

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

14 Oct
1 year ago

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

What about Windows users? any ideas

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

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?

07 Oct
1 year ago

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

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?

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?

@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?

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?

03 Oct
1 year ago

malhayek left a reply on How Do I Define An API Route?

@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?

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

@andreasbakir it corresponds to the model id.

02 Oct
1 year ago

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

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?

@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?

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?

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?

@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

01 Oct
1 year ago

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

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?

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?

28 Sep
1 year ago
27 Sep
1 year ago

malhayek left a reply on How Can I Change A Char Column Using Migrations?

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