PS: I am new to Laravel. And following this tutorial to create sample project
Everything is working fine.
But I am not able to figure out how data is inserted into the database.
here is the form code
<form method="post" action="{{url('products')}}">
{{csrf_field()}}
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<label for="name">Name:</label>
<input type="text" class="form-control" name="name" >
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<label for="price">Price:</label>
<input type="text" class="form-control" name="price">
</div>
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<button type="submit" class="btn btn-success" style="margin-left:38px">Add Product</button>
</div>
</div>
</form>
Here at the onsubmit action it is calling "{{url('products')}}" .
What is the mean of this? Can anybody help?
If you need any other code let me know.
web.php
<?php
Route::resource('products','ProductController');
Route::get('/', function () {
return view('welcome');
});
ProductController.php
<?php
namespace App\Http\Controllers;
use App\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
$products = Product::all()->toArray();
return view('products.index', compact('products'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
return view('products.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
$product = $this->validate(request(), [
'name' => 'required',
'price' => 'required|numeric'
]);
Product::create($product);
return back()->with('success', 'Product has been added');;
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
}
{{url('/products')}} means url() function will return base url and whatever added inside that method will append to base ur;
for example my website url is https://stackoverflow.com/ then above method will return
https://stackoverflow.com/products
in your route you have to define
Route::resource('products','ProductController');
Laravel route will point to your controller and method and in method you have a logic to insert into database
for better understanding
url()
The url function generates a fully qualified URL to the given path:
Ref:
https://laravel.com/docs/5.5/helpers#method-url
Also to learn more about route resource you can refer
https://laravel.com/docs/5.5/controllers#resource-controllers
What you are asking for is Generating Urls This means it uses your app base url with the other urls you have in the string argument. Therefore, url('products') is the same thing as http://yourwebsite.com/products as the action on your form i.e where the form will be submitted to.
The other counterpart is Urls for named routes I will add a caption here in case the document link breaks at any point:
You see. This means that in your one of your routes has that name which you use to generate a url.
Since some of these helper functions are new to you (supposing you are learning by following a tutorial), my recommendation is to open Laravel's documentation and see how things are by yourself.
This seems to be a Route::ressource called 'product' and redirecting to ProductController.
Related
This type of question has been asked before but not one addresses my particular query. I have tried all the solutions but non seem to work.
I am building a Blog with Laravel and this particular error occurs when I try to edit any of my posts. You are all encouraged to participate. thank you.
edit.blade.php
#extends('layouts.app')
#section('content')
#if(count($errors)>0)
<ul class="list-group">
#foreach($errors->all() as $error)
<li class="list-group-item text-danger">
{{$error}}
</li>
#endforeach
</ul>
#endif
<div class="panel panel-default">
<div class="panel-heading">
Edit post{{$post->title}}
</div>
<div class="panel-body">
<form action="{{ route('post.update', ['id'=>$post->id])}}" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" class="form-control" value="{{$post->title}}">
</div>
<div class="form-group">
<label for="featured">Featured Image</label>
<input type="file" name="featured" class="form-control">
</div>
<div class="form-group">
<label for="category">Select a Category</label>
<select type="file" name="category_id" id="category" class="form-control">
#foreach($categories as $category)
<option value="{{$category->id}}">{{$category->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea name="content" id="content" cols="5" rows="5" class="form-control" >{{$post->content}}</textarea>
</div>
<div class="form-group">
<div class="text-center">
<button class="btn btn-success" type="submit">Update Post</button>
</div>
</div>
</form>
</div>
</div>
#stop
PostController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Category;
use App\Post;
use Session;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('admin.posts.index')->with('posts', Post::all());
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$categories =Category::all();
if ($categories-> count()==0){
Session::flash('info', 'You must have some categories before attempting to create a post');
return redirect()->back();
}
return view('admin.posts.create')->with('categories', Category::all());
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'title'=> 'required|max:255',
'featured'=>'required|image',
'content'=>'required',
'category_id' => 'required'
]);
$featured=$request->featured;
$featured_new_name= time().$featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name);
$post=Post::create([
'title'=> $request->title,
'content'=> $request->content,
'featured'=> 'uploads/posts/' .$featured_new_name,
'category_id'=> $request->category_id,
'slug' => Str::slug($request->title)
]);
Session::flash('success', 'Post created Successfully');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$post=Post::find($id);
return view('admin.posts.edit')->with('post', Post::find($id)->with('categories', Category::all()));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$post =Post::find($id);
$this->validate($request, [
'title'=> 'required',
'content'=>'required',
'category_id'=>'required']
);
if($request->hasfile('featured')){
$featured=$request->featured;
$featured_new_name=time() . $featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name );
$post->featured=$featured_new_name;
}
$post->title=$request->title;
$post->content=$request->content;
$post->category_id=$request->category_id;
$post->save();
Session::flash('success', 'Your post was just updated.');
return redirect()->route('posts');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$post =Post::find($id);
$post->delete();
Session::flash('success', 'Your post was just Trashed.');
return redirect()->back();
}
}
Property [title] does not exist on the Eloquent builder instance
This error message is telling you that you are trying to load a property named 'title' on an entity of type 'Eloquent builder'.
Eloquent builder is the type of object which can be used to query the database. The results of a call to ->first() on an Eloquent builder instance would be a Property entity, which is likely what you want.
Please examine and share the code where the Property is being loaded from the database. Do you do something, such as ->first(), to execute the query?
My form:
<form action="{{route('settings.update')}}" method="POST">
#csrf
<div class="col-sm-3">
<div class="form-group">
<label for="avatar">Upload a new one:</label>
<input type="file" id="pic" name="pic"/>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Upload avatar</button>
</div>
</form>
My Controller:
public function update_settings($request)
{
$this->validate($request, [
'pic' => 'required|image'
]);
$path = $request->image->store('/img/');
Auth::user()->image = $path;
return view('pages.settings');
}
The error:
Too few arguments to function App\Http\Controllers\PagesController::update_settings(), 0 passed and exactly 1 expected
I am passing only the image file in the $request, but for some reason the controller doesn't see it, what am I doing incorrectly?
To obtain an instance of the current HTTP request via dependency injection, you should type-hint the Illuminate\Http\Request class on your controller constructor or method. The current request instance will automatically be injected by the service container:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
class UserController extends Controller
{
/**
* Store a new user.
*
* #param Request $request
* #return Response
*/
public function store(Request $request)
{
$name = $request->input('name');
//
}
}
Look well that in the method I am injecting the dependence of Illuminate\Http\Request
You need to add enctype='multipart/form-data' to your opening form tag
<form action="{{route('settings.update')}}" method="POST" enctype="multipart/form-data">
I am creating a profile section.
And show.blade.php is the profile edit part.
But I cannot see show.blade.php.
I got a following error.
Here is my code.
web.php
Route::resource('channels', 'ChannelController');
php artisan route:list in terminal. And this is the result.
app.blade.php once I click here I can jump to show.blade.php
<a class="dropdown-item" href="{{ route('channels.show', auth()->user()->channel->id) }}"> My Channel</a>
controller.php
<?php
namespace Laratube\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
ChannelController.php
<?php
namespace Laratube\Http\Controllers;
use Illuminate\Http\Request;
class ChannelController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show(Channel $channel)
{
return view('channels.show', compact('channel'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
show.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
{{ $channel->name }}
</div>
<div class="card-body">
<form id="update-channel-form" action="{{ route('channels.update', $channel->id) }}" method="POST" enctype="multipart/form-data">
#csrf
#method('PATCh')
<div class="form-group">
<label for="name" class="form-control-label">
Name
</label>
<input id="name" name="name" value="{{ $channel->name }}" type="text" class="form-control">
</div>
<div class="form-group">
<label for="description" class="form-control-label">
Description
</label>
<textarea name="description" id="description" cols="3" rows="3" class="form-control">
{{ $channel->description }}
</textarea>
</div>
<button class="btn btn-info" type="submit">Update</button>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
I tried following things.
php artisan cache:clear
composer update
composer dump-autoload
php artisan db:seed
But still it doesn't work.
I am glad if someone helps me out.
I guess, I have something wrong with my route. This route also did not work.
Route::resource('channels', 'ChannelController')->name('channels.show');
My guess (without your controller code) is that you didn't import the model Channel. The message is quite clear, it tries to retrieve the model class from it's current directory: Laratube\Http\Controllers\.
You didn't import the Channel Model in your controller.
Add the line in the top use section of your controller.
use Laratube\Channel;
//In Your Controller
<?php
namespace Laratube\Http\Controllers;
use Laratube\Channel;
use Illuminate\Http\Request;
class ChannelController extends Controller
{
//in show function
public function show()
{
$channel = Channel::get();
return view('channels.show', compact('channel'));
}
I'm trying to make a website where you can upload games and see them on the home page, but because I need a two-step form I can't directly send them to the database.
my controller:
public function createstep1(Request $request)
{
$naam = $request->session()->get('naam');
return view('games.game',compact('naam', $naam))->with('games', game::all());
}
public function postcreatestep1(Request $request)
{
$validatedData = $request->validate([
'naam' => 'required',
'geslacht' => 'required',
]);
if(empty($request->session()->get('naam'))){
return redirect('/game');
}else{
$naam = $request->session()->get('naam');
$naam->fill($validatedData);
$request->session()->put('naam', $naam);
}
return redirect('/newgame');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create(Request $request)
{
$naam = $request->session()->get('naam');
return view('games.newgame',compact('naam',$naam));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$game= new Game();
$game->game= $request['game'];
$game->naam= $request['naam'];
$game->geslacht= $request['geslacht'];
$game->save();
return redirect('/game');
}
<div id="newgame" style="height: 500px; width: 250px; float: left;">
<form method="post" name="naam">
#csrf
<input id="naam" name="naam" placeholder="naam">
<select name="geslacht" type="text">
<option name="man">man</option>
<option name="vrouw">vrouw</option>
</select>
<a type="submit"><button>volgende</button></a>
</form>
</div>
<div id="games" style="float: right">
#foreach($games as $game)
{{$game->game}} <br><br>
#endforeach
</div>
<h1>welkom {{$naam}}</h1>
<form method="post">
#csrf
<h3>game invoeren</h3>
<input type="text" id="gamenaam" name="gamenaam" placeholder="game">
<a id="submit" type="post" name="game" href="/newgame/store">
<button>verstuur</button></a>
</form>
Route::get('/', function () {
return view('welcome');
});
Route::get('/newgame', function () {
return view('games.newgame');
});
//Route::post('/newgames', ['as' => '/newgames', 'uses' => 'GameController#create']);
Route::get('/game', 'GameController#createstep1');
Route::post('/game', 'GameController#postcreatestep1');
Route::get('/newgame', 'GameController#create');
Route::post('/newgame/store', 'GameController#store');
I expect it will drop the game + name and gender in the database but the actual code gives an error message.
This work is for school but they can't help me if you have suggestions or can help me fix the problem that would be great.
When registering a new route you need to specify which HTTP method the route is for. Usually Route::get() is alright but since you're sending a POST request with your form to the controller method postcreatestep1, this one needs to be registered as a POST route with Route::post().
You may also declare a route available for multiple HTTP methods with the Route::match() method.
To get an overview of all available router methods the official documentation of Laravel is a good starting point.
Im doing a university project which is a foodlog, where the user is able to log in and then log their food items. Ideally this will post to the database, then the user will be able to view all their logged foods displayed in a table.
at the minute im trying to post the form information to the database and it doesnt seem to work. I also want the user's id to be logged in the database which is a foreign key in the food log table (from users table).
This is my PostsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
class PostsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store()
{
Post::create([
'id'->request('id');
'user_id'->Auth::user()->id;
'name'->request('name');
'servings'->request('servings');
'servingsize'->request('servingsize');
'calories'->request('calories');
'fat'->request('fat');
]);
return redirect('/foodlog');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
This is my add.blade.php
#extends('layouts.app')
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<form method="POST" action="/posts">
{{ csrf_field() }}
<h1>Add to Foodlog</h1>
<div class="form-group">
<label for="item">Item:</label>
<input type="text" id="name" name="name" class="form-control">
</div>
<div class="form-group">
<label for="noOfServings">Number of Servings:</label>
<input type="number" id="servings" name="servings" class="form-control">
</div>
<div class="form-group">
<label for="servingSize">Serving Size (g):</label>
<input type="number" id="servingsize" name="servingsize" class="form-control">
</div>
<div class="form-group">
<label for="calories">Calories (kcal):</label>
<input type="number" id="calories" name="calories" class="form-control">
</div>
<div class="form-group">
<label for="fat">Fat (g):</label>
<input type="number" id="fat" name="fat" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
</div>
</div>
</div>
#endsection
And my web.php
<?php
Route::get('/', 'FoodlogController#index');
Route::get('/add', 'FoodlogController#add');
Route::get('/account', 'FoodlogController#account');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/foodlog', function() {
return view('/foodlog');
});
Route::get('/logout', function(){
Auth::logout();
return Redirect::to('welcome');
});
Route::post('/posts', 'PostsController#store');
I have also included a screenshot of my create foodlog migrations file so that you can see the fields in my table
Also my Post model is empty as you can see
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
//
}
Your store function should looks like:
public function store(Request $request)
{
Post::create([
'id' => $request->id, //<--- if this is autoincrement then just delete this line
'user_id' => Auth::user()->id,
'name' => $request->name,
'servings' => $request->servings,
'servingsize' => $request->servingsize,
'calories' => $request->calories,
'fat' => $request->fat
]);
return redirect('/foodlog');
}
For relationship between tables please follow this link
Add to Post model fillable fields:
protected $fillable = [
//if id is not autoincrement then add 'id'
'user_id',
'name',
'servings',
'servingsize',
'calories',
'fat'
];