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

anonymouse703's avatar

How to set variable in a try catch function?

Trying refactor store using try catch and I want to make a variable to identify edit or store but it's not working

public function store(){

        $action = null;   

        try
		{
            
			$data = $this->validate([
                'name' => 'required',
            ]);
            if($this->roleId){
                Role::find($this->roleId)->update($data);
                $action = 'edit';
            }else{
                Role::create($data);
                $action = 'store';
            }

		} catch (\Exception $e) {


			return back()->with('error',$data);

		}

        if($action = 'store'){
            session()->flash('message', 'Role successfully created.');
        }
        else{
            session()->flash('message', 'Role successfully updated.');
        }
        
        $this->resetInputFields();
        $this->emit('refreshParent');
        $this->emit('closeRoleModal');

    }

I got this warning Symbol '$action' is declared but not used.intelephense(1003)

0 likes
12 replies
SilenceBringer's avatar

@anonymouse703 first of all, I think it should be == here

if($action == 'store'){

second one - I think you need to move validation outside of try-catch (Validation Exception has it's own handler, and you prevent it)

And the last one - why you introduce action at all, if you can replace if($action == 'store') with

if(!$this->roleId)
anonymouse703's avatar

the flash message is not firing...

update code from your suggestion:

  public function store(){

        try
		{
            
			$data = $this->validate([
                'name' => 'required',
            ]);
            if($this->roleId){
                Role::find($this->roleId)->update($data);
            }else{
                Role::create($data);
            }

		} catch (\Exception $e) {


			return back()->with('error',$data);

		}

        if(!$this->roleId){
            session()->flash('success', 'Role successfully created.');
        }
        else{
            session()->flash('success', 'Role successfully updated.');
        }
        
        $this->resetInputFields();
        $this->emit('refreshParent');
        $this->emit('closeRoleModal');

    }

I separated the flash images into separate file

@if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
    <button type="button" class="close" data-dismiss="alert">×</button>    
    <strong>{{ $message }}</strong>
</div>
@endif
  
@if ($message = Session::get('error'))
<div class="alert alert-danger alert-block">
    <button type="button" class="close" data-dismiss="alert">×</button>    
    <strong>{{ $message }}</strong>
</div>
@endif
   
@if ($message = Session::get('warning'))
<div class="alert alert-warning alert-block">
    <button type="button" class="close" data-dismiss="alert">×</button>    
    <strong>{{ $message }}</strong>
</div>
@endif
   
@if ($message = Session::get('info'))
<div class="alert alert-info alert-block">
    <button type="button" class="close" data-dismiss="alert">×</button>    
    <strong>{{ $message }}</strong>
</div>
@endif
  
@if ($errors->any())
<div class="alert alert-danger">
    <button type="button" class="close" data-dismiss="alert">×</button>    
    Please check the form below for errors
</div>
@endif

and include it in the app.blade.php

  <div id="container" class="effect aside-float aside-bright mainnav-lg">
            
            @include('layouts.flash_messages.flash-message')

            <div class="boxed">
            @include('layouts.shared.header')
                <div  id="content-container">
                    <div id="page-content">
                        <main>
                            {{ $slot }}
                        </main>
                    </div>
                </div>

                @include('layouts.shared.main_nav')
            </div>

            @include('layouts.shared.footer')

        </div>
SilenceBringer's avatar

@anonymouse703 are you sure you don't end up in the catch block?

try

		} catch (\Exception $e) {
			dd($e);
			return back()->with('error',$data);
		}
anonymouse703's avatar

@SilenceBringer The new data is still stored in the database but the problem is the flash message doesn't display.. @include('layouts.flash_messages.flash-message') I include it in here app.blade.php

<body>
       
        <div id="container" class="effect aside-float aside-bright mainnav-lg">
            
            <div class="boxed">
                @include('layouts.shared.header')
                <div  id="content-container">
                @include('layouts.flash_messages.flash-message')
                    <div id="page-content">
                        <main>
                            {{ $slot }}
                        </main>
                    </div>
                </div>

                @include('layouts.shared.main_nav')
            </div>

            @include('layouts.shared.footer')



        </div>

        @stack('modals')

        <!-- Scripts -->
        @livewireScripts
        <script type="text/javascript" src="{{ mix('js/app.js') }}"></script>
        <script type="text/javascript" src="{{ mix('js/main.js') }}"></script>
        <!-- <script type="text/javascript" src="{{ asset('js/DataTable.js') }}"></script> -->
        @yield('custom_script') 
       
    </body>
anonymouse703's avatar

@Sinnbeck The new data is still stored in the database but the problem is the flash message doesn't display.. @include('layouts.flash_messages.flash-message') I include it in here app.blade.php

<body>
       
        <div id="container" class="effect aside-float aside-bright mainnav-lg">
            
            <div class="boxed">
                @include('layouts.shared.header')
                <div  id="content-container">
                @include('layouts.flash_messages.flash-message')
                    <div id="page-content">
                        <main>
                            {{ $slot }}
                        </main>
                    </div>
                </div>

                @include('layouts.shared.main_nav')
            </div>

            @include('layouts.shared.footer')



        </div>

        @stack('modals')

        <!-- Scripts -->
        @livewireScripts
        <script type="text/javascript" src="{{ mix('js/app.js') }}"></script>
        <script type="text/javascript" src="{{ mix('js/main.js') }}"></script>
        <!-- <script type="text/javascript" src="{{ asset('js/DataTable.js') }}"></script> -->
        @yield('custom_script') 
       
    </body>
SilenceBringer's avatar

@anonymouse703 I think the problem is that your success messages included outside of livewire components, and they don't refreshed on livewire re-render

anonymouse703's avatar

@SilenceBringer My boss want to include it in the app.blade like in a ordinary laravel project and always said that it's a livewire and we have arguments. the reason why he wants to put it in the app.blade to make it global and reusable.

I already include it in the table view component

<div>
<div class="row">
        <div class="col-xs-12">
            @include('layouts.flash_messages.flash-message') //Flash message blade
            <div class="panel">
                <div class="panel-heading">
                    <h3 class="panel-title">Permissions</h3>
                </div>

                <!--Data Table-->
                <!--===================================================-->
                <div class="panel-body">
                    <div class="pad-btm form-inline">
                        <div class="row">
                            <div class="col-sm-6 table-toolbar-left">
                                <button class="btn btn-purple" wire:click="createPermission"><i class="demo-pli-add icon-fw"></i>Add</button>
                                <!-- <button class="btn btn-default"><i class="demo-pli-printer icon-lg"></i></button> -->
                            </div>
                        </div>
                    </div>
                    <div wire:key="permissions" class="table-responsive">
                        <table id="permissionTable" class="table table-striped table-bordered" cellspacing="0" width="100%"> 
                            <thead>
                                <tr>
                                    <th>Permission</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse ($permissions as $data)
                                <tr>
                                    <td>{{$data->name}}</td>
                                    <td class="text-center align-middle">
                                        <div class="btn-group">

                                            <button wire:click="editPermission({{ $data->id }})" class="btn btn-info delete-header m-1 btn-sm"  title="Edit"><i class="fa fa-pencil" aria-hidden="true"></i></button>

                                            <button wire:click="deleteConfirmPermission({{ $data->id }})" class="btn btn-danger delete-header m-1 btn-sm"  title="Delete"><i class="fa fa-trash-o" aria-hidden="true"></i></button>

                                        </div>                
                                    </td>
                                </tr>
                            
                                @empty
                                    <tr>
                                        <td style="text-align:center" colspan="2">No Record Found</td>
                                    </tr>
                                @endforelse   
                            </tbody>
                        </table>
                    </div>
                </div>
                <!--===================================================-->
                <!--End Data Table-->

            </div>
            <!-- The Modal -->
            <div wire.ignore.self class="modal fade" id="permissionModal" tabindex="-1" role="dialog" aria-labelledby="permissionModal" aria-hidden="true" data-backdrop="static" data-keyboard="false">
                <div class="modal-dialog" role="document">
                    <livewire:auth.permission-form />
                </div>
            </div>
        </div>
    </div>
</div>
@section('custom_script')
    @include('layouts.scripts.permission-scripts'); 
@endsection

and try this

public function store(){

        $action == '';

        $data = $this->validate([
            'name' => 'required',
        ]);

        try
		{
            if($this->permissionId){
                Permission::find($this->permissionId)->update($data);
            }else{
                Permission::create($data);
            }

		} catch (\Exception $e) {
			return back();
            $action = 'error';
		}

        if(!$this->permissionId){
            $action = 'edit';
        }
        else{
            $action = 'store';
        }
        
        $this->emit('showEmitedFlashMessage', $action);
        $this->resetInputFields();
        $this->emit('refreshParent');
        $this->emit('closePermissionModal');

    }

But I got this error Undefined variable: action. If I don't use try catch everything is okay but he wants to use us try catch so that it will also throw error if failed to store in database.

} catch (\Exception $e) {
			return back();
            $action = 'error';
		}
anonymouse703's avatar
anonymouse703
OP
Best Answer
Level 6

Solution: Instead of making a blade file for flash messages. I created a flash message component and included it in parent component.. to be able to flash the images I created lister to past the value of the action.

Please or to participate in this conversation.