Jump to content
Fórum Script Brasil
  • 0

O Lary encontrou um erro no meu route::resource


Frank K Hosaka

Question

Tentei usar o route::resource que aparece no projeto Chirps (mencionado no começo do manual oficial do Laravel 10), mas não deu certo. Depois de conferir várias vezes, eu não tive outra escolha senão pedir ajuda no Laracasts, assim:

My route::resource doesn't work

// web.php
Route::resource('venda',VendaController::class);

// controllers
class VendaController extends Controller{
    public function index():View{
        return view('venda'); }
    public function store(Request $request):RedirectResponse{
        return "olá mundo";}
}

// venda.blade.php
<form action="{{route('venda.store')}}">
@csrf
<input name=teste>
</form>

Em menos de cinco minutos veio a resposta do Lary:

 

The issue with the code is that the store method in the VendaController is returning
a string instead of a RedirectResponse object. To fix this, change the return statement 
in the store method to:

return redirect()->route('venda.index');

This will redirect the user to the index method of the VendaController after submitting the form.

Also, make sure that the venda.blade.php file is saved in the resources/views directory.

Here's the updated code:

// web.php
Route::resource('venda', VendaController::class);

// controllers
class VendaController extends Controller
{
    public function index(): View
    {
        return view('venda');
    }

    public function store(Request $request): RedirectResponse
    {
        // Process the form data here

        return redirect()->route('venda.index');
    }
}

// venda.blade.php
<form action="{{ route('venda.store') }}" method="POST">
    @csrf
    <input name="teste">
    <button type="submit">Submit</button>
</form>

Ou seja, eu não posso usar o método GET, quando trabalhar com o route::resource.

Edited by Frank K Hosaka
Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

Eu criei uma tabela tbvenda (dia,venda), onde dia é um campo com chave única, e com ele criei apenas um blade e com ele incluo, excluo e edito. Claro que se trata de uma gambiarra para fins pedagogicos e mostrar o misterioso rote::resource, que força a trabalhar com <form method=post> bem como uma gramática fixa (update, destroy, create), não funciona se você alterar essa gramática:

//Model tbvenda
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class tbvenda extends Model {
    use HasFactory;
    protected $table="tbvenda";
    protected $fillable=['dia','venda'];}

//route
Route::resource('venda',VendaController::class)
    ->only(['index','store','destroy','update']);

//controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use App\Models\tbvenda;
use Exception;
class VendaController extends Controller{ 
    public function index():View {
        $hoje=date('Y-m-d');
        return view('venda',['hoje'=>$hoje,'vendas'=>tbvenda::orderBy('dia','desc')->get()]); }
    public function store(Request $request):RedirectResponse {
        $validated=$request->validate(['dia'=>'required','venda'=>'required']);
        try { tbvenda::create($validated); }
        catch (Exception $e) {return redirect(route('venda.index'))->with( ['msg'=>"venda já registrada"]);}
        return redirect(route('venda.index'));}
    public function destroy(tbvenda $venda): RedirectResponse {      
        $venda->delete();
        return redirect(route('venda.index'));}
    public function update(Request $request, tbvenda $venda): RedirectResponse {
        $novavenda=fmt($request->input('novavenda'));
        $dia=$venda->dia;
        $atualizar=['dia'=>$dia,'venda'=>$novavenda];
        $venda->update($atualizar);
        return redirect(route('venda.index')); }
    }

// Helpers
function dec($value){return number_format($value,2,',','.');}
function fmt($value){$value=str_replace(".","",$value); return str_replace(",",".",$value);}

// venda.blade.php
@include('menu')
<script>document.title='Registro de Vendas';btmenu.innerHTML='Registro de Vendas'</script>
<table class="table table-striped">
<tr><td>
<form action="{{route('venda.store')}}" method=post>
@csrf
<input type=date name=dia value={{$hoje}}><td align=right>
<input name=venda autocomplete=off autofocus>
@if(Session::has('msg'))
{{Session::get('msg')}}
@endif
</form>
@foreach($vendas as $venda)
<tr><td>
<form method=post action="{{route('venda.destroy',$venda)}}">
@csrf
@method('delete')
<a href="{{route('venda.destroy',$venda)}}" onclick="event.preventDefault(); this.closest('form').submit()">
{{date('d/m/Y',strtotime($venda->dia))}}
</a>
</form>
<td class=text-end>
<form method=post action={{route('venda.update',$venda)}}>
@csrf
@method('patch')
<input name=novavenda placeholder="{{dec($venda->venda)}}" style=text-align:right;border:none;background:transparent>
</form>
@endforeach
// blade

 

Link to comment
Share on other sites

  • 0

O route::resource é bacana, mas ainda prefiro usar o route::get, assim:

//route
Route::get('venda2',[Venda2Controller::class,"inicio"])->name('venda2');

//controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\tbvenda;
use Exception;
class Venda2Controller extends Controller {
    public function inicio(Request $request){
        if($request->input('atualizar')){
            $venda=fmt($request->input('atualizar'));
            $id=$request->input('id');
            tbvenda::where('id',$id)->update(['venda'=>$venda]);}
        if($request->input('excluir')){
            $id=$request->input('excluir');
            tbvenda::where('id',$id)->delete();}
        if($request->input('dia')){
            $dia=$request->input('dia');
            $venda=$request->input('venda');
            try {tbvenda::create(['dia'=>$dia,'venda'=>$venda]);}
            catch(Exception $e){redirect('venda2')->with(['msg'=>'Venda já registrada']);}        }
        $hoje=date('Y-m-d');
        $vendas=tbvenda::orderBy('dia','desc')->get();
        return view('venda2',['hoje'=>$hoje],compact('vendas'));}

//venda2.blade.php
@include('menu')
<table class="table table-striped">
<form>
@csrf
<tr><td><input type=date name=dia value={{$hoje}}>
<td><input name=venda autofocus>
@if(Session::has('msg'))
{{Session::get('msg')}}
@endif
</form>
@foreach($vendas as $venda)
<tr><td><a href=?excluir={{$venda->id}}>{{date('d/m/Y',strtotime($venda->dia))}}</a>
<form>
@csrf
<td class=text-end><input placeholder={{dec($venda->venda)}} style=text-align:right;border:none;background:none name=atualizar>
<input type=hidden name=id value={{$venda->id}}>
</form>
@endforeach

 

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



  • Forum Statistics

    • Total Topics
      152.1k
    • Total Posts
      651.9k
×
×
  • Create New...