Laravel 5.2 FatalErrorException in casasController.php line 51 - laravel

i need your help. i'm building a webApp in Laravel5.2. This is the probles i can't solve...FatalErrorException in casasController.php line 51; i really dont know what to do...the odject is correctly declared in namespace and its saved once validate!
This is my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Oggetto;
use App\Categoria;
use DB;
use Session;
class casasController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$oggetti = DB::table('casas')->get();
$categoriasSelect = DB::table('categorias')->get();
return view('pages.casa')->with('categoriasSelect', $categoriasSelect)->with('oggetti', $oggetti);
}
/**
* 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)
{
$this->validate($request, [
'nome' => 'required',
'categoria' => 'required',
'descrizione' => 'required'
]);
$oggetto = new Oggetto;
$oggetto->nome = $request->nome;
$oggetto->categoria = $request->categoria;
$oggetto->descrizione = $request->descrizione;
$status = $request->nome;
$oggetto->save();
Session::flash('success', 'Il tuo oggetto per la casa รจ stato salvato con successo!');
return view('pages.casa')->with('oggetto', $oggetto);
}
/**
* 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)
{
//
}
}
These are my routes:
Route::get('/', 'pagesController#index');
Route::group(array('prefix' => 'luogo'), function(){
Route::get('casa',['as' => 'opzione1', 'uses' => 'casasController#index']);
Route::get('parco',['as' => 'opzione2', function(){
return view('pages.parco');
}]);
Route::get('stazione',['as' => 'opzione3', function(){
return view('pages.stazione');
}]);
});
Route::post('nome', ['as' => 'nomeInput', 'uses' => 'pagesController#form']);
//Authentication Routes(login) -->built in
Route::get('auth/login', ['as' => 'login', 'uses' => 'Auth\AuthController#getLogin']);
Route::post('auth/login', ['as' => 'loginPost', 'uses' => 'Auth\AuthController#postLogin']);
Route::get('auth/logout', [ 'as' => 'logout', 'uses' => 'Auth\AuthController#getLogout']);
//Registration Routes(new users) -->built in
Route::get('auth/register', ['as' => 'register', 'uses' => 'Auth\AuthController#getRegister']);
Route::post('auth/register', 'Auth\AuthController#postRegister');
Route::post('categoria', ['as' => 'categ', 'uses' => 'categoriasController#newCat']);
Route::resource('oggetto/{status?}', 'casasController', ['except' => ['show']]);
This is my view:
#extends('main')
#section('content')
<h1 class="text-center">Benvenuto a Casa</h1>
<h3 class="text-center"> Aggiungi un oggetto</h3>
<div class="row">
<div class="col-md-8 col-md-offset-2">
#if(count($errors) > 0)
#foreach($errors->all() as $error)
<div class="alert alert-danger">{{$error}}</div>
#endforeach
#elseif(Session::has('success'))
<div class="alert alert-success">{{Session::get('success')}}</div>
#endif
<table class="table table-striped">
<thead>
<tr>
<th>Nome</th>
<th>Categoria</th>
<th>Descrizione</th>
<th colspan="2">Azioni</th>
</tr>
</thead>
<tbody>
#foreach($oggetti as $oggetto)
<tr>
<td>{{$oggetto->nome}}</td>
<td>{{$oggetto->categoria}}</td>
<td>{{$oggetto->descrizione}}</td>
<td><button type="button" class="btn btn-info btn-block">Editare</button></td>
<td><button type="button" class="btn btn-danger btn-block">Cancellare</button></td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
<div class="row" id="formOggetto" style="display: none; margin-top: 25px">
<div class="col-md-8 col-md-offset-2">
<form action="{{action('casasController#store')}}" method="POST">
<input type="hidden" name="_token" value="{{csrf_token()}}"/>
<div class="form-group">
<label for="nome">Nome</label>
<input type="text" class="form-control" id="nome" name="nome" placeholder="Nome">
</div>
<div class="row">
<div class="col-md-8">
<div class="form-group">
<label for="categoria">Categoria</label>
<select class="form-control" name="categoria">
<option value="null">Scegli...</option>
#foreach($categoriasSelect as $categoriaSelect)
<option>{{$categoriaSelect->nome}}</option>
#endforeach
</select>
</div>
</div>
<div class="col-md-4">
<label>Aggiungi nuova categoria</label>
<button type="button" class="btn btn-warning btn-block" data-toggle="modal" data-target="#modalCateg">Aggiungi</button>
</div>
</div>
<div class="form-group">
<label for="descrizione">Descrizione</label>
<textarea type="text" class="form-control" id="descrizione" name="descrizione" placeholder="Descrizione"></textarea>
</div>
<input type="submit" class="btn btn-primary btn-block" value="Salva">
</form>
</div>
</div>
#stop

Ok, you don't have Oggetto model, so you need to create it first.
Also change this:
$oggetto = new Oggetto;
to this:
$oggetto = new Oggetto();

Related

laravel - SQLSTATE[HY000]: General error: 1364 Field 'password' doesn't have a default value

*Asking for your help again please. Im getting the above error on registration module. This is working before. I tried to make a my profile edit page and then this happens. Hoping for your help please.. Thank you in advance *
User Controller:
namespace App\Http\Controllers\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Model\user\user;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
class UserController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$user = Auth::user();
return view('user.user.show',compact('user'));
}
/**
* 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)
{
$this->validate(request(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed'
]);
$user = User::create([
'name' => request('name'),
'email' => request('email'),
]);
$user->password = bcrypt(request('password'));
auth()->login($user);
return redirect(route('index'));;
}
/**
* 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)
{
$user = Auth::user();
return view('user.user.edit', compact('user'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate(request(), [
'email' => ['required','email',Rule::unique('users')->ignore($id)],
'password' => ['required','password',Rule::unique('users')->ignore($id)]
]);
//$user = Auth::user();
$user = Auth::user();
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->firstname = $request->firstname;
$user->middlename = $request->middlename;
$user->lastname = $request->lastname;
$user->nationality = $request->nationality;
$user->gender = $request->gender;
$user->civilstatus = $request->name;
$user->mobilenum = $request->mobilenum;
$user->worknum = $request->worknun;
$user->workadd = $request->workadd;
$user->homeadd = $request->homeadd;
$user->email = $request->email;
$user->birthday = $request->birthday;
$user->save();
return redirect(route('user.user.show'))->with('message','Announcement Updated Succesfully');;
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
Blade file:
<form method="POST" action="{{ route('register') }}">
#csrf
<div class="text-center"><button class="btn btn-primary text-left" style="width: 100%;" type="button"><i class="fa fa-facebook"></i> Continue with Facebook</button></div>
<div class="text-center mt-2"><button class="btn btn-light text-left border-dark" style="width: 100%;" type="button"><i class="fa fa-google"></i> Continue with Google</button></div>
<form class="mt-4">
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend"><span class="text-primary input-group-text"><i class="fa fa-user-o"></i></span></div><input class="form-control #error('name') is-invalid #enderror" name="name" value="{{ old('name') }}" required autocomplete="name" autofocus placeholder="Full Name">
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
<div class="input-group-append"></div>
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend"><span class="text-primary input-group-text"><i class="fa fa-envelope-o"></i></span></div><input class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email" placeholder="Email">
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
<div class="input-group-append"></div>
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend"><span class="text-primary input-group-text"><i class="fa fa-lock"></i></span></div><input class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="new-password" placeholder="Password" type="password">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
<div class="input-group-append"></div>
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend"><span class="text-primary input-group-text"><i class="fa fa-lock"></i></span></div><input class="form-control" name="password_confirmation" required autocomplete="new-password" placeholder="Confirm Password" type="password">
<div class="input-group-append"></div>
</div>
</div>
Model/users/user.php
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'firstname', 'middlename', 'lastname', 'birthday', 'nationality',
'gender', 'civilstatus', 'mobilenum', 'worknum', 'workadd',
'homeadd',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Please help me. Thank you in advance
The reason you're getting this issue is because password isn't mass assignable i.e. it isn't in your $fillable array.
Methods like create() or fill() are protected from mass assignment. To get around this you can either add password to your $fillable array or set it explicitly e.g.
public function store(Request $request)
{
$this->validate(request(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed',
]);
$user = new User([
'name' => request('name'),
'email' => request('email'),
]);
$user->password = bcrypt(request('password'));
$user->save();
auth()->login($user);
return redirect(route('index'));;
}
You can do two things:
Make your table definition so the password can be nullable
Use the new User([...]) syntax over User::create([...]). The first one does not insert directly, the latter will.
Table definition example:
Schema::create('users', function ($table) {
// other user table fields ...
$table->string('password')->nullable();
});
Example without ::create (as given by #Rwd):
// NOT User::create([...]) but new User([...]);
$user = new User([
'name' => request('name'),
'email' => request('email'),
]);
$user->password = bcrypt(request('password'));
$user->save(); // dont forget to save when not using ::create([...]) syntax

Missing required parameters for [Route: berita.update]

I'm trying to get the parameter id_berita, it appears in url, but when i want to show the previous data it can't....
Controller
class KontenController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth:admin');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
$berita = Berita::all();
return view('backpages/berita', compact('berita'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('backpages.berita_input'); //untuk menampilkan form add
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
request()->validate([
'id_berita' => 'required',
'id_kategori' => 'required',
'username' => 'required',
'tanggal' => 'required',
'judul' => 'required',
'isi' => 'required',
]);
Berita::create($request->all());
$request->session()->flash('pesan','Berita '.$request['id_berita'].' berhasil disimpan.');
return redirect()->route('berita.index');
}
/**
* Display the specified resource.
*
* #param \App\Berita $berita
* #return \Illuminate\Http\Response
*/
public function show(Berita $berita)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Berita $berita
* #return \Illuminate\Http\Response
*/
public function edit(Berita $berita)
{
// return view('backpages.berita_edit',compact('berita'));
$berita = Berita::find($berita);
// return view('backpages.berita_edit')->with('berita',$berita);
return view('backpages.berita_edit')->with('berita', $berita);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Berita $berita
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Berita $berita)
{
request()->validate([
'username' => 'required',
'tanggal' => 'required',
'judul' => 'required',
'isi' => 'required',
]);
$berita->update($request->all());
$request->session()->flash('pesan','Berita '.$request['judul'].' berhasil
diperbarui.');
return redirect()->route('berita.index');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Berita $berita
* #return \Illuminate\Http\Response
*/
public function destroy(Berita $berita)
{
//
}
}
berita_edit.blade.php for update process
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">Edit Berita</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form action="{{route('berita.update')}}" method="POST">
{{ csrf_field() }}
{{method_field('PUT')}}
<div class="card-body">
<div class="form-group">
<label for="exampleInputPassword1">Username</label>
<input type="text" class="form-control" name="username" placeholder="Username" value="{{ $berita->username }}">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Tanggal</label>
<input type="date" class="form-control" name="tanggal" placeholder="Tanggal" value="{{ $berita->tanggal }}">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Judul</label>
<input type="text" class="form-control" name="judul" placeholder="Judul" value="{{ $berita->judul }}">
</div>
<div class="form-group">
<label>Isi</label>
<textarea class="form-control" rows="3" name="isi" value="{{ $berita->isi }}" placeholder="Enter ..."></textarea>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
For displaying data
<div class="card-body table-responsive p-0">
<table class="table table-hover text-nowrap">
<thead>
<tr>
<th>id_Berita</th>
<th>id_Kategori</th>
<th>Username</th>
<th>Tanggal</th>
<th>Judul</th>
<th>Isi</th>
<th colspan="2" style="text-align:left">Opsi</th>
</tr>
</thead>
<tbody>
#foreach($berita as $data)
<tr>
<td>{{$data -> id_berita}}</td>
<td>{{$data -> id_kategori}}</td>
<td>{{$data -> username}}</td>
<td>{{$data -> tanggal}}</td>
<td>{{$data -> judul}}</td>
<td>{{$data -> isi}}</td>
<td>
<a class="btn btn-block btn-info" href="{{ route('berita.edit', $data -> id_berita) }}"?>Edit</a>
</td>
<td>
<a class="btn btn-block btn-info" href="#"?>Hapus</a>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
You have to change action like this
<form action="{{route('berita.update',['berita'=>$berita->id])}}" method="POST">
<a class="btn btn-block btn-info" href="{{ route('berita.edit', ['berita'=>$data->id_berita]) }}"?>Edit</a>

How do I deal with controller resource in laravel

I am using the resource tool for my controller and my route but the store method appears not to work. Could you highlight what I did wrong. Is the controller name needs to be the same as the model one? I am confuse
FarmController
<?php
namespace App\Http\Controllers;
use App\Animal;
use Auth;
use Illuminate\Http\Request;
class FarmController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$animal = Animal::all();
return view('farms.index', compact('animal'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$user = Auth::user();
$animal = new Animal();
return view('farms.create', compact('user', 'animal'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store()
{
Animal::create($this->validateRequest());
return redirect('farms.show');
}
private function validateRequest()
{
return request()->validate([
'dateOfBirth' => 'required|date',
'placeOfBirth' => 'required',
'gender' => 'required',
'user_id' => 'required',
]);
}
Animal.php (controller)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Animal extends Model
{
protected $guarded = [];
public function user(){
return $this->belongsTo(User::class);
}}
animals (table)
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAnimalsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('animals', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id')->index();
$table->date('dateOfBirth');
$table->string('gender');
$table->string('placeOfBirth');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('animals');
}
}
create.blade.php
#extends('layouts.app')
#section('title', 'Add Animal')
#section('content')
<div class="row">
<div class="col-12">
<h1>Farm</h1>
</div>
</div>
<h3>Welcome {{ $user->name }} Please Add an animal</h3>
<div class="row">
<div class="col-12">
<form action="{{ url('farms') }}" method="POST">
<div class="form-group">
<label for="dateOfBirth">Date Of Birth: </label>
<input type="date" name="dateOfBirth" class="form-control" placeholder="dd/mm/yyyy">
</div>
<div class="pb-5">
{{ $errors->first('dateOfBirth') }}
</div>
<div class="form-group">
<label for="placeOfBirth">Place Of Birth</label>
<input type="text" name="placeOfBirth" class="form-control">
</div>
<div class="pb-5">
{{ $errors->first('placeOfBirth') }}
</div>
<div class="form-group">
<label for="gender">Gender: </label>
<select name="gender" class="form-control">
<option value="M">Male</option>
<option value="F">Female</option>
</select>
</div>
<div class="form-group">
<label for="user">User</label>
<select class="form-control" name="user">
<option value="{{ $user->id }}" name="user">{{ $user->name }}</option>
</select>
</div>
<button type="submit" class="btn btn-primary">Add Farm</button>
#csrf
</form>
</div>
</div>
#endsection
web.php (routes)
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::middleware('admin')->group(function () {
// All your admin routes go here.
Route::resource('/admin', 'AdminController');
});
Route::middleware('farms')->group(function () {
// All your admin routes go here.
Route::resource('/farms', 'FarmController');
});
When I am submitting the form, it seems like it just refreshes the page and do not add anything in my table. I have been stuck on this in two entire days. any help is welcome
In the validateRequest function you have
'user_id' => 'required',
But your form in the view has no field named user_id
The select element is named user
<select class="form-control" name="user">
<option value="{{ $user->id }}" name="user">{{ $user->name }}</option>
</select>
Change one of them so they can match, I guess that the page refresh is just failed validation
You may want to check for any validation error in your view to find out what's wrong as per the docs
For example
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Hope this helps
Just change your form action then it hit in correct mehtod. Here is the action for your form
{{route('farms.store')}}

How to insert a row in Laravel given that one field does not have a default value?

I try to insert the session user id in form but it was show me error this:
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into stocks (product_name, product_code, details, price, cost, quntity, updated_at, created_at) values (basmati Rice, 23432, dskljsdlkks;lk; ;ks;lvk, 40, 75, 100kg, 2019-09-09 08:43:12, 2019-09-09 08:43:12))
I think error on this line of code which I used for store the session id
<input type="hidden" name="user_id"
value="{{ $request->session()->put('user',$request->input('id')) }}"
> class="form-control">
This is my create blade page, which I make a form and try to insert the form fields.
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-md-12">
#if(count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
#if(\Session::has('success'))
<div class="alert alert-success">
<p>{{ \Session::get('success') }}</p>
</div>
#endif
<div class="card">
<div class="card-header">
<h5 class="title">Add New Product on Stock</h5>
</div>
<div class="card-body">
<form method="post" action="{{url('stock')}}">
{{csrf_field()}}
<div class="row">
<div class="col-md-6 pr-1">
<div class="form-group">
<label>Product Name</label>
<input type="text" name="user_id"
value="{{Auth::user()->id }}" class="form-control">
<input type="text" name="product_name" class="form-control" placeholder="Enter Product Name" />
</div>
</div>
<div class="col-md-6 pl-1">
<div class="form-group">
<label>Product Code</label>
<input type="text" name="product_code" class="form-control" placeholder="Enter product_code" />
</div>
</div>
</div>
</br>
<div class="row">
<div class="col-md-4 pr-1">
<div class="form-group">
<label>Price</label>
<input type="text" name="price" class="form-control" placeholder="Enter price" />
</div>
</div>
<div class="col-md-4 px-1">
<div class="form-group">
<label>Cost</label>
<input type="text" name="cost" class="form-control" placeholder="Enter cost" />
</div>
</div>
<div class="col-md-4 pl-1">
<div class="form-group">
<label>Quantity</label>
<input type="text" name="quntity" class="form-control" placeholder="Enter quntity" />
</div>
</div>
</div>
</br>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Details</label>
<input type="text" name="details" class="form-control" placeholder="Enter details" />
</div>
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" />
</div>
</form>
</div>
</div>
#endsection
this is my controller file of stock
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Stock;
use Auth;
class StockController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$stocks = Stock::all()->toArray();
return view('stock.index', compact('stocks'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('stock.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'user_id' =>'required',
'product_name' => 'required',
'product_code' => 'required',
'details' => 'required',
'price' => 'required',
'cost' => 'required',
'quntity' => 'required'
]);
$stock = new Stock([
'user_id' => Auth::user()->user_id,
'product_name' => $request->get('product_name'),
'product_code' => $request->get('product_code'),
'details' => $request->get('details'),
'price' => $request->get('price'),
'cost' => $request->get('cost'),
'quntity' => $request->get('quntity')
]);
$stock->save();
return redirect()->route('stock.index')->with('success', 'Data Added');
}
/**
* 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)
{
$stock = Stock::find($id);
return view('stock.edit', compact('stock', '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)
{
$this->validate($request, [
'product_name' => 'required',
'product_code' => 'required',
'details' => 'required',
'price' => 'required',
'cost' => 'required',
'quntity' => 'required'
]);
$stock = Stock::find($id);
$stock->product_name = $request->get('product_name');
$stock->product_code = $request->get('product_code');
$stock->details = $request->get('details');
$stock->price = $request->get('price');
$stock->cost = $request->get('cost');
$stock->quntity = $request->get('quntity');
$stock->save();
return redirect()->route('stock.index')->with('success', 'Data Updated');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$stock = Stock::find($id);
$stock->delete();
return redirect()->route('stock.index')->with('success', 'Data Deleted');
}
}
You don't have to use the $request->input('id') to get the user id .
Simply use
Session::flash(Auth::user()->id);
For your code ,
<input type="hidden" name="user_id"
value="{{Auth::user()->id, Session::flash(auth::user()->id) }}"
> class="form-control">
And in your controller ,
when you are trying to save the user_id variable ,
EDIT ::::
$stock = new Stock([
'user_id' => Auth::user()->id,
'product_name' => $request->get('product_name'),
'product_code' => $request->get('product_code'),
'details' => $request->get('details'),
'price' => $request->get('price'),
'cost' => $request->get('cost'),
'quntity' => $request->get('quntity')
]);
Use the session variable to store ,.
Or you can directly store the user_id using Auth::user()->id in that line ,
'user_id' => Auth::user()->user_id,
change this:
$request->session()->put('user',$request->input('id'))
to like this:
Session::set('user',$request->input('id'));
Make attention, you need pass the $request to your view, so you can use the request data. Otherwise create a variable $user_id and pass it to your view blade. in this case you can do:
Session::set('user',$user_id);

PostTooLarge Exception Laravel

I have uploaded 15mb image and it throws exception of PostTooLarge Exception instead of exception i have to show flash error message but could not get it.
below is the handler i have used for Handler.php it works great but not display flash message.
if ($exception instanceof \Illuminate\Http\Exceptions\PostTooLargeException)
{
return redirect()->route('users.add')->withFlashError('Image Size too large!');
}
then i tried validate of laravel for image in my controller which is as below
$validator = Validator::make($request->all(), [
'image' => 'max:4000',
]);
if ($validator->fails())
{
return redirect()->route('user')->withFlashError('Image size exceeds 4MB');
}
but still no luck
below is blade file with form:
<form method="post" action="{{route('users.submit')}}" id="adduser" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<div class="form-row">
<div class="form-group col-md-6">
<label class="col-form-label">User name*</label>
<input type="text" class="form-control" name="name" placeholder="User name" value="{{ old('name') }}">
</div>
<div class="form-group col-md-6">
<label class="col-form-label">User email*</label>
<input type="text" class="form-control" name="email" value="{{ old('email') }}" placeholder="User email" autocomplete="off">
</div>
</div>
</div>
<div class="form-group">
<div class="form-row">
<div class="form-group col-md-6">
<label class="col-form-label">Password*</label>
<input id="password" type="password" class="form-control" name="password" placeholder="Password">
</div>
<div class="form-group col-md-6">
<label class="col-form-label">Confirm password</label>
<input type="password" class="form-control" name="confirmpassword" placeholder="Confirm password">
</div>
</div>
</div>
<div class="form-group">
<div class="form-row">
<div class="form-group col-md-6">
<label class="col-form-label">Phone number*</label>
<input type="text" class="form-control" name="mobile" value="{{ old('mobile') }}" placeholder="Phone Number">
</div>
<div class="col-md-6">
<label class="col-form-label">User role*</label>
<select name="role" class="form-control valid">
<option value="">Select Role</option>
<option {{ old('role')==3?'selected':'' }} value="3">Author</option>
<option {{ old('role')==5?'selected':'' }} value="5">Product Admin</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<div class="form-row">
<div class="col-md-6">
<label class="col-form-label">User image</label>
<div class="card-body">
<div class="was-validated">
<label class="custom-file">
<input type="file" name="image" accept=".jpg, .png,.jpeg" id="file" class="custom-file-input">
<span class="custom-file-control"></span>
</label>
<ul class="preview" style="margin-top: 10px;">
</ul>
</div>
</div>
</div>
</div>
</div>
<button style="float: right;" type="submit" class="btn btn-primary" id="validateForm">Save</button>
</form>
and below is controller code :
<?php
namespace App\Http\Controllers\admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Validator;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$users = User::whereNotIn('role', array(1,4))->orderBy('id','DESC')->get();
return view('admin.users.index',compact('users'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.users.add');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$data=$request->all();
$validate = Validator::make($data, [
'email' => 'required|string|email|max:255|unique:users',
]);
if ($validate->fails()) {
return redirect('users/add')->withFlashError('Email already exists')->withInput();
}
if(isset($_FILES['image']))
{
$validator = Validator::make($request->all(), [
'image' => 'max:4000',
]);
if ($validator->fails())
{
//return redirect()->route('user')->withFlashError('Image size exceeds 4MB');
//return redirect()->route('user')->withErrors(['error' => 'Image size exceeds 4MB']);
//return redirect('users/add')->withFlashError('Image size exceeds 4MB')->withInput();
return redirect()->back()->withErrors(['error' => 'Image size exceeds 4MB']);
}
if(basename($_FILES['image']['name']) != "")
{
$target_path = base_path().'/public/user/';
$time=round(microtime(true));
$newfilename = $target_path .$time . '.jpg';
$target_path = $target_path .time().basename($_FILES['image']['name']);
if (move_uploaded_file($_FILES['image']['tmp_name'], $newfilename))
{
$user_data['image'] =$time.'.jpg';
}
}
else
{
$user_data['image'] = "";
}
}
$insert_data = array
(
"name" => $data['name'],
"email" => $data['email'],
"password" => bcrypt($data['password']),
"mobile" => $data['mobile'],
"image" => $user_data['image'],
"role" => $data['role'],
"status" => 1
);
User::create($insert_data);
return redirect()->route('users')->withFlashSuccess('User added 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)
{
//
}
/**
* 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)
{
$user = User::find($id);
$user->delete();
return redirect()->route('users')->withFlashSuccess('User deleted successfully');
}
public function delete($id)
{
$news = User::find($id);
$news->delete();
}
public function status($id)
{
$store=User::find($id);
if($store->status==1)
{
$status=0;
}
else
{
$status=1;
}
User::whereId($id)->update(array('status'=>$status));
return redirect()->route('users')->withFlashSuccess('User status changed');
}
public function saverole(Request $request)
{
$data=$request->all();
$string_role = implode(', ', $data['role']);
User::whereId($data['user_id'])->update(array('role'=>$string_role));
return redirect()->route('users')->withFlashSuccess('User role changed');
}
}
Change your validate line of code to this:
$this->validate(request(), [
'image' => 'max:4000'
],
[
'image.max' => 'Image size exceeds 4MB'
]);
And inside your view file, run this code to display the errors:
#if($errors->any())
<h4>{{$errors->first()}}</h4>
#endif
Because the php.ini stands first while throwing exception, it will not carry forward that expectation to your defined errors.

Resources