We help IT Professionals succeed at work.

Could you point why a Laravel Controller method produces an error when another similar runs correctly?

Eduardo Fuerte
on
Medium Priority
45 Views
Last Modified: 2020-02-17
Hi Experts

Could you point why a Laravel Controller method produces an error when another similar runs correctly?

Accordingly to:

JS
function Vitrine() {}
 

//OK
Vitrine.prototype.salvar = function(){
  
  $.ajax({
    url: '/vitrine/salvar',
    
    method: "POST",
    data: {
      _token: $('input[name="_token"]').val(),
      id: $('#id').val(),
      url: $('#url').val(),
      inicio: $('#inicio').val(),
      termino: $('#termino').val(),
      title: $('#title').val(),
      description: $('#description').val(),
      points: $('#points').val()
    },
    error:function(data){
      hotsite.openModalCustom("Erro", data.responseText, "Entendi", "error");
    },
    success: function(data){
      hotsite.openModalCustom("Sucesso ao salvar", data.retorno, "Entendi", "success");
      hotsite.closeModal('mEditor');
      //hotsite.vitrine.filtrar();
    }
  });
};


// This doesn't runs correctly
Vitrine.prototype.minhasfotos = function(){
  $.ajax({
    url: '/vitrine/minhasFotos',
    method: "GET",
    dataType: "html",
    error:function(data){
      hotsite.openModalCustom("Erro", "Erro ao carregar vitrine.", "Entendi", "error");
    },
    success: function(data){
      $('#midiaList').html(data);
    }
  });
}

Open in new window



Laravel routes:
Route::post('/vitrine/salvar',['uses'=>'VitrinesController@salvar'])->middleware('cadastro');   // OK
Route::post('/vitrine/minhasfotos',['uses'=>'VitrinesController@minhasFotos'])->middleware('cadastro');  //NOK

//This route apparently is called somehow....
Route::get('/vitrine/{id}/obter',['uses'=>'admin\VitrineController@obter'])->middleware('cadastro');

Open in new window



VitrinesController methods:
// Runs correctly
 public function salvar(Request $request){
        
        
        info("Em salvar...");

        $id=$request->input('id');
        $url=$request->input('url');
        $inicio=$request->input('inicio');
        $termino=$request->input('termino');

        $titulo = $request->input('titulo');
        $descricao = $request->input('descricao');
        
        $titulo = $request->input('title');
        $descricao = $request->input('description');
        //$pontuacao = $request->input('points');
  
        try{
            if($id != '' &&  $id > 0){
              $vitrine = Vitrine::find($id);
            }
  
            if(empty($vitrine)){
              $vitrine = new Vitrine();
              $vitrine->created_at=new \DateTime();
            }
                
            $vitrine->titulo = $titulo;
            $vitrine->descricao = $descricao;
            $vitrine->url = $url;
            $vitrine->updated_at=new \DateTime();

            $vitrine->criador_id = auth()->user()->id;

            $vitrine->save();
  
        } catch (\Exception $e) {
            
            info($e);
            return response()->json(new Resultado(true,'','Erro ao salvar a foto'), 400);
        }
  
        return response()->json(new Resultado(false,'','Sua foto foi enviada para análise da Copagaz, se for aprovada a foto ficará visível para todos os participantes.'));
    
    }
	
	
// This method generates an error with  apparently no relation with VitrinesController (but with VitrineController)


    public function minhasFotos(Request $request){
        
		// Just to check call
        info('em minhasFotos');
       
    }

Open in new window




Web page
Runs OK
        <button type="button" class="btn btn-primary" onclick="hotsite.vitrine.salvar();"><i class="fas fa-hdd" aria-hidden="true"></i> Salvar</button>
		
Generates Error
		<button type="button" class="btn btn-primary" onclick="hotsite.vitrine.minhasfotos();">

Open in new window



The error pointed at another Controller (VitrineController.php)

img011

img012

Could you check and point a workaround?

Thanks in advance
Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019
Commented:
Hey Eduardo,

You need to get your route and your request to match. Your route is set up to respond to a POST request, but your Javascript is making a GET request:

$.ajax({
    url: '/vitrine/minhasFotos',
    method: "GET",

Route::post('/vitrine/minhasfotos',['uses'=>'VitrinesController@minhasFotos'])->middleware('cadastro');  //NOK

They'll need to match.

Because your Javascript is making a GET request to url: '/vitrine/minhasFotos', it's assuming you're making a GET request to this route:

Route::get('/vitrine/{id}/obter',['uses'=>'admin\VitrineController@obter'])->middleware('cadastro');

So it's trying to call the obter method on your VitrineController and pass the value of 'minhasfotos' as the ID, which is clearly wrong.
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Hi Chris

So I did this adjust:

Route::get('/vitrine/minhasfotos',['uses'=>'VitrinesController@minhasFotos'])->middleware('cadastro');

Open in new window


But the same error remains...
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Adjusted it also


Vitrine.prototype.minhasfotos = function(){
  $.ajax({
    url: '/vitrine/minhasfotos',
    method: "GET",
    dataType: "html",
    error:function(data){
      hotsite.openModalCustom("Erro", "Erro ao carregar vitrine.", "Entendi", "error");
    },
    success: function(data){
      $('#midiaList').html(data);
    }
  });
}


Before

    url: '/vitrine/minhasFotos',

Open in new window



Now it's running...
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Chris


Thank you for the help!
CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019

Commented:
Excellent. Good spot on the typo. I missed that.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.