Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

msabiry's avatar

All other crud working except Update

Hello dear Please help me how can I fix this issue My code won't work on update Controller:

<?php

namespace App\Http\Controllers;

use App\Company;
use App\Customer;
use Intervention\Image\Facades\Image;

class CustomerController extends Controller
{

    // Extends middleware('Auth')
    // Only Authorized Users can access this routes
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $activeUser = Customer::active(); // Active is a scope from Model
        $inactiveUser = Customer::inactive(); // Inactive is a scope from Model
        $companies = Company::all();

        return view('customer', compact('activeUser', 'inactiveUser', 'companies'));
    }

    // Create Records
    public function create()
    {
        $companies = Company::all();
        $customer = new  Customer();
        return view('customer', compact('companies', 'customer'));
    }

    // Save Records
    public function store()
    {
        $customer = Customer::create($this->validateRequest()); // Getting data from validateRequest() function

        $this->storeImage($customer);

//        event(new NewCustomerHasRegisteredEvent($customer));

        return back()->with('success', 'Added Successfully!');
    }

    // Show Records
    public function show(Customer $customer)
    {
        $companies = Company::all();
        return view('profile', compact('customer', 'companies'));
    }

    // Edit Records
    public function edit(Customer $customer)
    {
        $companies = Company::all();
        return view('profile', compact('customer', 'companies'));
    }

    // Update Records
    public function update(Customer $customer)
    {
        $customer->update($this->validateRequest());

        $this->storeImage($customer);

        return back();
    }

    // Delete Records
    public function destroy(Customer $customer)
    {
        $customer->delete();
        return redirect('customers');
    }

    public function validateRequest()
    {
        return tap(request()->validate([
            'fName' => 'required|max:24',
            'lName' => 'required|max:24',
            'email' => 'required|max:64|email|unique:customers',
            'message' => 'nullable',
            'active' => 'required',
            'company_id' => 'required',
        ]), function (){
            if (request()->has('image')){
                request()->validate([
                    'image' => 'file|image|max:5000'
                ]);
            }
        });
    }

    public function storeImage($customer)
    {
        if (request()->has('image')){
            $customer->update([
                'image' => request()->image->store('images', 'public'),
            ]);

            $image = Image::make(public_path('storage/' . $customer->image))->fit(60, 60, null, 'top-left');
            $image->save();
        }
    }
}

my Blade:

<div class="modal fade" id="edit" tabindex="-1" role="dialog" aria-labelledby="editLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <p class="modal-title" id="editLabel" style="font-size: medium; font-weight: bold;">Edit</p>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form class="form-group" method="post" enctype="multipart/form-data" action="{{ route('customers.update', ['customer' => $customer]) }}">
                @method('PATCH')
                @csrf
                <div class="modal-body">
                    <div class="form-group">
                        <label for="fName" class="col-form-label">First Name:</label>
                        <input type="text" name="fName" class="form-control" placeholder="First Name" style="border-bottom: 2px; font-size: small;" value="{{ old('fName') ?? $customer->fName }}">
                    </div>

                    <div class="form-group">
                        <label for="fName" class="col-form-label">First Name:</label>
                        <input type="text" name="lName" class="form-control" placeholder="Last Name" style="border-bottom: 2px; font-size: small;" value="{{ old('lName') ?? $customer->lName }}">
                    </div>

                    <div class="form-group">
                        <label for="text" class="col-form-label">Message:</label>
                        <textarea name="message" id="message" class="form-control" style="border-bottom: 2px; font-size: small;" placeholder="Message...">{{ old('message') ?? $customer->message }}</textarea>
                    </div>
                    <div class="form-group">
                        <label for="active" class="col-form-label">Status:</label>
                        <select name="active" id="active" class="form-control">
                            <option value="" disabled>Select an option</option>
                            @foreach($customer->activeOptions() as $activeOptionKey => $activeOptionValue)
                                <option value="{{ $activeOptionKey }}" {{ $customer->active == $activeOptionValue ? 'selected' : '' }}>
                                    {{ $activeOptionValue }}
                                </option>
                            @endforeach
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="company_id" class="col-form-label">Company:</label>
                        <select name="company_id" id="company_id" class="form-control">
                            @foreach($companies as $company)
                                <option value="{{ $company->id }}"
                                        {{ $company->id == $customer->company_id ? 'selected' : '' }}>
                                    {{ $company->name }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="form-group d-flex flex-column">
                        <label for="image" class="col-form-label">Profile Picture:</label>
                        <input type="file" accept="image/*" name="image" class="py-2">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Save</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </form>
        </div>
    </div>
</div>

my route:

Route::resource('customers', 'CustomerController');
0 likes
32 replies
Nasmed's avatar

Hi,

Please share your code or the error message, so we can help you.

msabiry's avatar

@NASMED Hi bro I can add post and it stores Then when I update records it won't work

jlrdw's avatar

Read the docs on file storage and uploading and make sure you're uploading the image correctly.

msabiry's avatar

@JLRDW - Everything is ok with it Storing, viewing and deleting records works correctly, but editing won't work I can't update my records

edoc's avatar

can you store a record with no problem?

jlrdw's avatar

What happens if you change patch to post. Also try put.

msabiry's avatar

@EDOC - Yes bro I can store data without any problem, but can't update And it doesn't show any error

msabiry's avatar

@EDOC - It says: MethodNotAllowedHttpException The POST method is not supported for this route. Supported methods: GET, HEAD, PUT, PATCH, DELETE.

Nasmed's avatar

Try this approach to update the image:

public function storeImage($customer)
{   
    if (request()->has('image')) {
        $customer->image = request()->get('image')->store('images', 'public');
        $customer->save();

        $image = Image::make(public_path('storage/' . $customer->image))->fit(60, 60, null, 'top-left');
        $image->save();
    }
}
Snapey's avatar

Form action should match what it says in php artisan route::list for the update function, which for update will be PUT or PATCH

jlrdw's avatar

And also I don't know your routes but a post will always work if you're updating a record. I usually use put for just a simple update.

Normally I just use regular routes no resource routes and I've never had a problem with post or put.

I have never used patch I've never seen the need for it.

Supported methods: GET, HEAD, PUT, PATCH, DELETE.

GET it's not usually used for an update.

Snapey's avatar

by the way (and not in answer to your question)

{{ old('message') ?? $customer->message }}

old() supports the default as a second parameter, so the above can be

{{ old('message', $customer->message) }}

Works the same though.

Snapey's avatar

can you dd($customer) at the top of your update method to make sure a) the routing is ok, and b) the route model binding is working ok. You should see a dump of the customer specified in the route.

Do you have standard incrementing ID's for the primary key?

When you edit, does the form pre-populate from the model?

msabiry's avatar

@SNAPEY - It works but after this code It didn't work $customer->update($this->validateRequest());

msabiry's avatar

@SNAPEY - I tried old on your way but still not working bro Logically and technically my code is best and should work but I don't know where is the problem

msabiry's avatar

@JLRDW - Resource works with all of them It makes simple your code, My code works with resource completely with all methods of CRUD except update

Snapey's avatar

So if the next line is not executed after the validation then you have a validation error.

Are you displaying errors?

Have you Laravel debugbar, this will show session and errors.

Snapey's avatar

Validation rule for email will fail because you don't exclude the current record.

(not to mention the fact that you don't even have email in your form)

msabiry's avatar

@SNAPEY - No I haven't laravel debugger. See this is my validation and hasn't any error It works for store but won't work for update,

public function validateRequest()
    {
        return tap(request()->validate([
            'fName' => 'required|max:24',
            'lName' => 'required|max:24',
            'email' => 'required|max:64|email|unique:customers',
            'message' => 'nullable',
            'active' => 'required',
            'company_id' => 'required',
        ]), function (){
            if (request()->has('image')){
                request()->validate([
                    'image' => 'file|image|max:5000'
                ]);
            }
        });
    }
Snapey's avatar

If you don't want to give the user the option to change their email, then you need a different set of rules for update.

But you MUST have a way to show validation errors

Snapey's avatar

    'email' => [
        'required',
        'max:64',
        Rule::unique('customers')->ignore($customer),
    ],
msabiry's avatar

@SNAPEY - It didn't know Rule: The error is right now: Class 'App\Http\Controllers\Rule' not found

Snapey's avatar

You have to import classes you use.

at the top of the controller;

use Illuminate\Validation\Rule;
Snapey's avatar

Well it will be the same if email rule is required because you don't have email field on your update form.

Next

Please or to participate in this conversation.