Posting content into the database with an image using Laravel - php

I'm trying to post some stuff into the database using laravel, but It seems not to work...
This is what I get:
The HTML:
{{ Form::open(array('role' => 'form')) }}
<div class="form-body">
<div class="form-group">
<label>Titel</label>
<input type="text" class="form-control" name="title" placeholder="Titel komt hier">
</div>
<div class="form-group">
<label>Textarea</label>
<textarea class="form-control" name="message" rows="5" placeholder="Uw bericht..."></textarea>
</div>
<div class="form-group">
<label for="exampleInputFile1">Nieuws afbeelding</label>
<input type="file" name="img">
</div>
</div>
<div class="form-actions">
<input type="submit" class="btn green" value="Oplsaan" />
</div>
{{ Form::close() }}
#if ($errors->any())
<ul>
{{ implode('', $errors->all('<li class="error">:message</li>')) }}
</ul>
#endif
That displays all well....
Exept when I try to 'post' the news, because that is what I try to do, it just refreses the page. The URL to that page is mydomain.com/admin/news/write
My router looks like this:
Route::resource('admin/news/write', 'AdminController#create');
First it was authenticated in a group:
Route::group(array('before' => 'auth'), function()
{
Route::resource('admin', 'AdminController');
Route::resource('admin/news/write', 'AdminController#create');
});
This all works, but when I change the Route::resource('admin/news/write', 'AdminController#create'); to Route::post('admin/news/write', 'AdminController#create'); I get an error, that I can't see...
Good, now my controller:
public function store()
{
$rules = array(
'title' => 'required',
'message' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->passes())
{
if (Input::only('title', 'message'))
{
return Redirect::to('admin/news/write')->with('message', 'Het nieuws werd gemaakt!');
}
}
else
{
return Redirect::to('admin/news/write')->with('message', "Er ging iets mis: ")->withErrors($validator);
}
}
The problem is, I don't know how I can store an image to
/public/pictures/news
And then store the full file name into the database, if someone could help me out... I need a response quick, beacause I have a deadline... :{
Kindest regards

First you need to tell your form using the laravel helper that this is going to be uploading a file...
Form::open(['method'=>'POST', 'role' => 'form', 'files' => true])
In your controller you want to get the file from the input
$imgFile = Input::file('img');
Now to move the file from the temporary location it's been uploaded, to a more permanent location call the following (where $filename is what you want to call the uploaded file)...
$dir = '../storage/app/upload/';
$imgFile->move($dir.$filename);
The path for the root of the app from here is ../ (one up from public) so..
../storage/app/upload/ would be a great location to use for uploaded files.
You can then just write:
$dir.$filename;
back to the database - job done :)
Edit :: -- Your Controller --
Your controller for parsing this is based on resources...
So your route will be:
Route::group(array('before' => 'auth'), function()
{
Route::resource('admin', 'AdminController');
}
Your controller itself will have a structure such as (remembering this: http://laravel.com/docs/4.2/controllers#restful-resource-controllers):
class AdminController extends BaseController {
public function index(){...}
public function create(){...}
public function
//The store() method is an action handled by the resource controller
//Here we're using it to handle the post action from the current URL
public function store()
{
$imgFile = Input::file('img');
//processing code here....
}
public function show(){...}
public function edit(){...}
public function update(){...}
public function destroy(){...}
}

I fixed the issue.
My controller:
<?php
class AdminNewsController extends \BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
return View::make('admin.news.create');
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
return View::make('admin.news.create');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
$rules = array(
'title' => 'required',
'message' => 'required',
'publish' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
//process the storage
if ($validator->fails())
{
Session::flash('error_message', 'Fout:' . $validator->errors());
return Redirect::to('admin/news/create')->withErrors($validator);
}else{
//store
$news = new News;
$news->title = Input::get('title');
$news->message = Input::get('message');
$news->img_url = Input::file('img')->getClientOriginalName();
$news->posted_by = Auth::user()->username;
$news->published_at = time();
$news->published = Input::get('publish');
$news->save();
//save the image
$destinationPath = 'public/pictures/news';
if (Input::hasFile('img'))
{
$file = Input::file('img');
$file->move('public/pictures/news', $file->getClientOriginalName());
}
//redirect
Session::flash('success', 'Nieuws succesvol aangemaakt!');
return Redirect::to('admin/news/create');
}
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
//
}
}
My create.blade.php
<div class="portlet-body form">
{{ Form::open(['method'=>'POST', 'role' => 'form', 'files' => true]) }}
<div class="form-body">
<div class="form-group">
<label>Titel</label>
<input type="text" class="form-control" name="title" placeholder="Titel komt hier">
</div>
<div class="form-group">
<label>Textarea</label>
<textarea class="form-control" name="message" rows="5" placeholder="Uw bericht..."></textarea>
</div>
<div class="form-group">
<label>Nieuws afbeelding</label>
{{ Form::file('img') }}
</div>
<div class="form-group">
<label>Bericht publiceren?</label>
<div class="radio-list">
<label class="radio-inline">
<span>
{{ Form::radio('publish', '1') }}
</span>
<b style="color:green">Publiceren</b>
</label>
<label class="radio-inline">
<span>
{{ Form::radio('publish', '0', true) }}
</span>
<b style="color:red">Niet publiceren</b>
</label>
</div>
</div>
</div>
<div class="form-actions">
<input type="submit" class="btn green" value="Oplsaan" />
</div>
{{ Form::close() }}
</div>
Then It all work!
Thanks to Matt Barber for the help!

Related

Property [title] does not exist on the Eloquent builder instance, PHP LARAVEL

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?

Laravel: create a button that affect a column in my database

Is it possible to create a button that changes a column value in a table?
I have a column named status in my movimentations table, and I was wondering if it is possible to change the value of this column with a button in my view that can change from active to inactive
this is my view
<div class="container">
<label for="name" class="form-group"><b>Nome</b>: {{ $movs->nameCoop }}</label><br>
<label for="name"><b>Numero</b>: {{ $movs->numCoop }}</label><br>
<label for="name"><b>CPF</b>: {{ $movs->cpfCoop }}</label><br>
<label for="name"><b>Cadastro</b>: {{ $movs->dtCad }}</label><br>
<label for="name"><b>Demissão</b>: {{ $movs->dtDem }}</label><br>
<label for="name"><b>Observações</b>: {{ $movs->description }}</label><br>
<label for="name"><b>Subscritas</b>: {{ $movs->subscritas }}</label><br>
<label for="name"><b>A integralizar</b>: {{ $movs->aintegralizar }}</label><br>
<label for="name"><b>Integralizadas</b>: {{ $movs->integralizadas }}</label><br>
<label for="name"><b>Status</b>: {{ $movs->status }}</label><br>
<td>
<form action="/trans" method="POST">
#csrf
<div class="input-group">
<input type="hidden" class="form-control" name="r" value={{$cooperado->id}}>
<button type="submit" class="btn btn-primary">
<span>+</span>
</button>
</span>
</div>
</form>
</td>
<td>
<form action="/mvs" method="POST">
#csrf
<div class="input-group">
<input type="hidden" class="form-control" name="v" value={{$cooperado->id}}>
<button type="submit" class="btn btn-primary">
<span>ver mvs</span>
</button>
</span>
</div>
</form>
</td>
this is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Cooperado;
class CooperadoController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
//$cooperados = Cooperado::all();
$cooperados = Cooperado::orderBy('dtCad', 'desc')->paginate(10);
return view('cooperados.index', compact('cooperados'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
return view('cooperados.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
$request->validate([
'nameCoop'=>'required',
'numCoop'=> 'required|integer',
'cpfCoop'=> 'required',
'dtCad'=>'required|date',
'subscritas'=>'required'
]);
$cooperado = new Cooperado([
'nameCoop' => $request->get('nameCoop'),
'numCoop'=> $request->get('numCoop'),
'cpfCoop'=> $request->get('cpfCoop'),
'dtCad'=> $request->get('dtCad'),
'description'=> $request->get('description'),
'subscritas'=> $request->get('subscritas'),
'aintegralizar'=> $request->get('subscritas'),
'status'=> $request->get('status')
]);
$cooperado->save();
return redirect('/cooperados')->with('success', 'Cooperado adicionado');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
$cooperado = Cooperado::find($id);
return view('cooperados.show', compact('cooperado'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
$cooperado = Cooperado::find($id);
return view('cooperados.edit', compact('cooperado'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
$request->validate([
'nameCoop'=>'required',
'numCoop'=> 'required|integer',
'cpfCoop'=> 'required',
'dtCad'=>'required|date',
'subscritas'=>'required'
]);
$cooperado = Cooperado::find($id);
$cooperado->nameCoop = $request->get('nameCoop');
$cooperado->numCoop = $request->get('numCoop');
$cooperado->cpfCoop = $request->get('cpfCoop');
$cooperado->dtCad = $request->get('dtCad');
$cooperado->dtDem = $request->get('dtDem');
$cooperado->description = $request->get('description');
$cooperado->subscritas = $request->get('subscritas');
$cooperado->integralizadas = $request->get('integralizadas');
$cooperado->aintegralizar = $request->get('aintegralizar');
$cooperado->status = $request->get('status');
$cooperado->save();
return redirect('/cooperados')->with('success', 'Cooperado atualizado');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
$cooperado = Cooperado::find($id);
$cooperado->delete();
return redirect('/cooperados')->with('success', 'Sucess');
}
}
I've tried to create a function in my route, but didn't work.
I added option button for active and inactive
<form action="/active-deactive" method="POST">
#csrf
<div class="input-group">
<input type="hidden" class="form-control" name="v" value="{{$cooperado->id}}">
<select required class="form-control" id="status" name="status">
<option value="1">Active</option>
<option value="0">De-Active</option>
</select>
</div>
<button type="submit" class="btn btn-primary">
<span>Confirm</span>
</button>
</div>
</form>
controller
public function Confirm(Request $request)
{
$id = $request->input('v');
$status=$request->input('status');
DB::table('tablename')
->where('id',$id)
->update(['status'=>$status]);
}
route
Route::post('/active-deactive','YourController#Confirm')
Of course you can. You can send a request via ajax when clicking on that button:
$.ajax({
type:'POST',
url:'{{ route("NameOfYourRoute") }}',
dataType:'json',
data:{
isActive = $('#theButtonID').val(),
_token = '<?php echo csrf_token() ?>'
},
success:function(data){
if (data.updated) {
alert('Data Updated');
}
}
});
Then in your controller, you can have a function that receives the value of the button (active or inactive) and updated your table in the database:
public function toggleActivity(Request $request)
{
$isActive = $request->get('isActive');
$updated = Model::where(yourCriteria)->update(['isActive' => $isActive]);
return view('YourView', compact('updated'));
}

Laravel 5.4 image gallery

I am building a Laravel web application where I need a dynamic image gallery, I build a backend admin panel where I can add images, I succeed to add and save the images to the database but I can not edit or delete them.
The error is:
ErrorException in UrlGenerationException.php line 17: Missing required parameters for [Route: galleries.update] [URI:
backend/galleries/{gallery}]. (View: /var/www/html/tryout101/resources/views/backend/gallery/edit.blade.php)
This my route code:
<?php
/*backend access*/
Route::group(['prefix' => '/backend'], function() {
/*The route Dashboard main page */
Route::get('/' , 'AdminController#index')->name('dashboard');
Route::resource('galleries' , 'GalleriesController');
});
This the Controller code:
<?php
namespace App\Http\Controllers;
use App\Gallery;
use Illuminate\Http\Request;
use Image;
use Illuminate\Support\Facades\Input;
class GalleriesController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$gallery = Gallery::all();
return view('backend.gallery.library', compact('gallery'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('backend.gallery.uploadform');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$gallery = new Gallery();
$this->validate($request, [
'title' => 'required',
'image' => 'required'
]);
$gallery->title = $request->title;
$gallery->description = $request->description;
if($request->hasFile('image')) {
$file = Input::file('image');
$filename = time(). '-' .$file->getClientOriginalName();
$gallery->image = $filename;
$file->move(public_path().'/images/', $filename);
}
$gallery->save();
return $this->create()->with('success', 'Image Uploaded
Successfully');
}
/**
* Display the specified resource.
*
* #param \App\Gallery $gallery
* #return \Illuminate\Http\Response
*/
public function show(Gallery $gallery)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Gallery $gallery
* #return \Illuminate\Http\Response
*/
public function edit(Gallery $gallery)
{
if(!$gallery){
return redirect('dashboard')->with(['fail'=>'post not found']);
}
return view('backend.gallery.edit',compact('gallery'));
}
public function update(Request $request, Gallery $gallery)
{
$this->validate($request, [
'title'=>'required|max:120',
'image'=>'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
$gallery->title = $request->title;
$gallery->description = $request->description;
if($request->hasFile('image')) {
$file = Input::file('image');
$filename = $file->getClientOriginalName();
$gallery->image = $filename;
$file->move(public_path().'images/', $filename);
}
$gallery->update();
return Redirect()->route('dashboard')->with(['success'=> 'post
successfully updated']);
}
public function destroy(Gallery $gallery)
{
//
}
}
/This is my edit page/
#extends('layouts.backend-master')
#section('styles')
<link rel="stylesheet" href="">
#endsection
#section('content')
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.
<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<h1>File Upload</h1>
<form action="{{route('galleries.update')}}" method="post"
enctype="multipart/form-data">
<div class="input-group">
<label for="title">Title</label>
<input type="text" name="title" id="title"/>
</div>
<div class="input-group">
<label for="description">Description</label>
<textarea type="text" name="description" id="description" rows="8">
</textarea>
</div>
<div class="input-group">
<label for="image">Select image to upload:</label>
<input type="file" name="image" id="file">
</div>
<button type="submit" class="btn">Update</button>
<input type="hidden" name="_token" value="{{Session::token()}}">
<input type="hidden" name="gallery" value="{{$gallery->id}}">
</form>
#endsection
#section('scripts')
#endsection
The fact is that the route 'galleries.update' requires a Gallery
Therefore, you should give him which Gallery you want to go to when calling the route function with that route
Thus, I think that changing
route('galleries.update')
into
route('galleries.update', $gallery)
will make everything fine

Login Form not working Laravel 5.2

I created a login form and a registration form in my eComerace Application but when I submit my login form ( sign in ) it returns nothing ! I have typed username and password correct but my login page is not working.
Routes
Route::get('users/signin', 'UsersController#getSignin');
Route::post('users/signin', 'UsersController#postSignin');
Route::resource('users', 'UsersController');
Route::get('/', 'StoreController#index');
Route::get('store/category/{id}', 'StoreController#getCategory');
Route::get('store/search', 'StoreController#getSearch');
Route::get('/admin', function () {
return view('welcome');
});
Route::resource('store', 'StoreController');
Route::resource('admin/categories', 'CategoriesController');
Route::resource('admin/products', 'ProductsController');
UsersController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use App\Http\Requests;
use App\Category;
use App\product;
use Hash;
use View;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
class UsersController extends Controller
{
public function __construct(){
parent::__construct();
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function getSignin(){
return View::make('users.signin');
}
public function index()
{
return Hash::make('ifti');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return View::make('users.newaccount');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$user = new User;
$user->name = Input::get('name');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->save();
return Redirect::to('users/signin')->with('message','Thank you for creating new account.Sign in now');
}
/**
* 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)
{
//
}
public function getSignout(){
Auth::logout();
return Redirect::to('users/signin')->with('message','Signouted!');
}
public function postSignin(){
$password = Hash::make(Input::get('password'));
$credentials = array('name' => Input::get('name'), 'password' => $password);
if(Auth::attempt($credentials)){
return Redirect::to('http://localhost/ecom/')->with('message','Thanks for signin');
}
return Redirect::to('users/signin')->with('message','Was Incorrect DATA!');
}
}
Signin View
{!! Form::open(array('url' => 'users/signin' , 'method' => 'post')) !!}
<div class="form-group">
<label for="username">User Name:</label>
{!! Form::text('name') !!}
</div>
<div class="form-group">
<label for="username">Password:</label>
{!! Form::password('password') !!}
</div>
<button type="submit" class="btn btn-default">Sign IN</button>
{!! Form::close() !!}
New Account View
<div class="col-md-8 col-lg-8 col-sm-12 col-xs-12">
{!! Form::open(array('url' => 'users/create' , 'method' => 'post')) !!}
<div class="form-group">
<label for="username">User Name:</label>
<input type="username" class="form-control" name="name" id="name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" name="email" id="name">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" name="password" id="name">
</div>
<button type="submit" class="btn btn-default">Create New Account</button>
{!! Form::close() !!}
</div>

Laravel 5: Data does not saved through blade form

I want to save a form input through Laravel 5.0
The page reloaded and back to the index page..But data does not save to mysql through routes.
Here is controller:
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Pagination\LengthAwarePaginator;
use App\Http\Requests\CreateTaskRequest;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Task;
use Input;
class TodoController extends Controller {
public function index()
{
$data=Task::all();
// $options=Option::whereNotIn('id',$activeCourse)->lists('option_name','id');
return view('home')->with('data',$data);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
//return view('home');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(CreateTaskRequest $request)
{
// dd($request->all());
/*$data=[
'name'=>Input::get('name'),
'status'=>Input::get('status'),
'description'=>Input::get('description'),
'task_img'=>Input::get('task_img'),
'dob'=>Input::get('dob')
];*/
$response=new Task();
$response->name=$request->input('name');
$response->status=$request->input('status');
$response->description=$request->input('description');
$response->description=$request->input('task_img');
$response->description=$request->input('dob');
$response->save();
// dd('working?');
//$response=Task::create(['name'=>$request->input('name'),'status'=>$request->input('status'),'description'=>$request->input('description')]);
if($response){
return redirect()->back()->with('success','Task Created Successfully');
}
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
$data=Task::find($id);
return view('todo_edit')->with('data',$data);
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update(CreateTaskRequest $request, $id)
{
$data=[
'name'=>Input::get('name'),
'status'=>Input::get('status')
];
$response=Task::find($id)->update($data);
if($response){
return redirect('/');
}
}
public function destroy($id)
{
$response=Task::find($id)->delete();
if($response){
return redirect('/')->with('success','Task Deleted Successfully');;
}
}
}
Here is my View Page:
#extends('app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-12 ">
<div class="col-lg-12">
<div class="col-lg-6">
{!! Form::open(array('route' =>'' ,'method'=>'post')) !!}
{!! Form::hidden('_token',csrf_token()) !!}
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Enter a task name"></br>
</br>
<lavel> <input name="status" type="radio" value="Complete"> Complete</lavel></br>
<label> <input checked="checked" name="status" type="radio" value="Incomplete"> Incomplete</label></br>
<textarea class="form-control" name="description" rows="3"></textarea></br>
<label>File input</label>
<input type="file" name="task_img"></br>
<input type="date" class="form-control datepicker" name="dob" style="width:95%">
{!! Form::submit('Save', array('class' => 'btn btn-primary')) !!}
</div>
{!! Form::close() !!}
</div>
</div>
<h3> Todo Application </h3>
<table class="table table-striped table-bordered" id="example">
<thead>
<tr>
<td>Serial No</td>
<td>Task Name</td>
<td>Status</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php $i=1; ?>
#foreach($data as $row)
<tr>
<td>{{$i}}</td>
<td>{{$row->name }}</td>
<td>{{$row->status}}</td>
<td>
Edit
<form action="{{route('postDeleteRoute',$row->id)}}" method="POST" style="display:inline;"
onsubmit="if(confirm('Are you sure?')) {return true} else {return false};">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class="btn btn-danger" value="Delete">
</form>
</td>
</tr>
<?php $i++; ?>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
#section('page-script')
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script>
$(document).ready(function() {
$('#example').DataTable();
} );
</script>
#stop
#endsection
And here is the routes :
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/',
'TodoController#index');
Route::post('/', 'TodoController#store');
Route::get('/{id}/edit',['as'=>'getEditRoute','uses'=>'TodoController#edit']);
Route::post('/{id}/edit',['as'=>'postUpdateRoute','uses'=>'TodoController#update']);
Route::post('/{id}/delete',['as'=>'postDeleteRoute','uses'=>'TodoController#destroy']);
//Route::get('home', 'HomeController#index');
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
To save data from a form you can do as below :
In you form replace
{!! Form::open(array('route' =>'' ,'method'=>'post')) !!}
with
{!! Form::open(array('route' =>'form.store' ,'method'=>'post')) !!}
In you route replace
Route::post('/', 'TodoController#store');
with
Route::post('/store',array('as'=>'form.store',uses=>'TodoController#store');
And in your controller replace
public function create()
{
//return view('home');
}
with
public function store(Request $request) //Http request object
{
Task::create($this->request->all());//assumes that you want to create task.
return \Redirect::route('/')->with('message', 'Task saved sucessfully!!!');
}
If you want to explore more then please read the documentation from the below links :
Laravel Routes
Laravel Request
Laravel Controllers
Hope it helps. Happy Coding :) .

Categories