VividDreams
VividDreams

Reputation: 93

Laravel null POST data in controller

A few days ago I started to learn laravel on laracasts and I have a small problem.

When I submit a form data using post method and want to access this data in my controller, I have an empty value.

Form:

<form method="POST" action="{{ url('/costs')}}">

{{ csrf_field() }}

  <div class="form-group">
    <label for="cost-title">Cost title</label>
    <input type="text" class="form-control" id="cost-title" name="title" placeholder="Enter cost title">
  </div>

  <div class="form-group">
    <label for="cost-price">Price</label>
    <input type="text" class="form-control" id="cost-price" name="price" placeholder="Enter price">
  </div>

  <button type="submit" class="btn btn-primary">Submit</button>
</form>

Controller:

<?php

namespace App\Http\Controllers;

use App\Cost;

class CostsController extends Controller
{
    public function index(){

        $costs = Cost::all();

        return view('costs.index', compact('costs'));

    }

    public function show(Cost $cost){

        return view('costs.show', compact('cost'));

    }

    public function create(Cost $cost){

        return view('costs.create');

    }

    public function store(){
        dd(request()->all);
    }
}

In my routes I'm triggering @store using post method:

Route::get('/costs', 'CostsController@index');
Route::get('/cost/{cost}', 'CostsController@show');
Route::get('/costs/create', 'CostsController@create');

Route::post('/costs', 'CostsController@store');

And when I try to dump and die the requests:

public function store(){
        dd(request()->all);
    }

I have a null value. Can you please explain me why I can't see any data here?

Upvotes: 3

Views: 11079

Answers (1)

Junaid Ahmad
Junaid Ahmad

Reputation: 599

Update your store method and pass a Request parameter like this:

 public function store (Request $request)
{
 $input = $request->all();
 dd($input);
}

Update:

The Illuminate\Http\Request

instance provides a variety of methods for examining the HTTP request for your application and extends the

Symfony\Component\HttpFoundation\Request

If your controller method is also expecting input from a route parameter you should list your route parameters after your other dependencies. For example, if your route is defined like so:

Route::put('user/{id}', 'UserController@update');

You may still type-hint the Illuminate\Http\Request and access your route parameter id by defining your controller method as follows:

public function update(Request $request, $id)
{
    //
}

So, in simple words for getting form parameters you have to pass a variable ($request) to your controller so that it can be accessible (lets just say that laravel store these form parameters in the $request variable, so you can easily pass it to controller or not). Hope it will clear up things :)

Upvotes: 4

Related Questions