Ad

How To Send Data From Blade View To Controller In Laravel To Preform A Post Request

- 1 answer

I am trying to favorite and unfavorite posts and insert it in favorites table if clicked and if clicked again it deletes it from favorites table i put my routes in web.php file the functions in the controller which should be called in the route are not called i insert there dd() method to test it so i am guessing the problem is in the form action and not sending the data

<body>

...

@foreach ($posts as $post)
    <div class="column">
        @if ($post->showstar == true)
            <form action="/favorites/delete" method="post">
                <span class="foo fa fa-star checked"></span>
            </form>
        @endif

        <h2>{{$post->title}}</h2>
        <img src={{$post->url}} >
    </div>
@endforeach
</body>

<script>
    $(document).ready(function () {
        $("form").on("click", ".foo", function () {
            if ($(this).hasClass("checked")) {
                $(this).removeClass("checked");
            } else {
                $(this).addClass("checked");
            }
        });
    });
</script>

Controller:

class FavoritesController extends Controller
{
    public function index()
    {
        return view('Favorites', ['favs' => Favorite::where('user_id', '1')->get()]);
    }

    public function view(Request $request)
    {
        dd("hello");
        $fav = new Favorite();
        $fav->user_id = $request->get('userid');
        $fav->post_id = $request->get('postid');
        $fav->save();
    }

    public function delete(Request $request)
    {
        dd("bye");
        $fav = new Favorite();
        $dfav = $fav->where('id', $request->id);
        $dfav->delete();

        return view('favorites');
    }

    public function fetch(Request $request)
    {
        $fav = new Favorite();
        $favs = $fav->where('user_id', $request->user_id);

        return view('favorites', compact('favs'));
    }
}

Routes:

Route::post('/favorites', '[email protected]');
Route::post('/favorites/delete', '[email protected]');
Route::post('/favorites/fetch', '[email protected]');
Ad

Answer

You could always try the plain and simple html form submit.

<form action="/favorites/delete" method="post">
  @csrf
  <input type="hidden" name="id" value="{{ $post->id }}">
  <button>
    <span class="foo fa fa-star checked"></span>
  </button>
</form>

This way you can send the hidden input, post id in your case, to the controller and it will delete it.

Ad
source: stackoverflow.com
Ad