How to update only 3 column value in Laravel? - php

I have a page model. It has following columns in database table:
id
name
email
password
status
privilege
usr_prf_color
usr_prf_nav
usr_prf_scroll
I want to update only 3 column value which are usr_prf_color, usr_prf_nav and usr_prf_scroll.
Here's my controller code:
public function themeUpdate(UpdateThemeRequest $request , User $user)
{
$user->update($request->all());
$request->usr_prf_color;
$request->usr_prf_nav;
$request->usr_prf_scroll;
$this->validate($request, [
'usr_prf_color' =>['required'],
'usr_prf_nav' => ['required'],
'usr_prf_scroll' => ['required'],
]);
$validatedData = $request->validated();
$data = $request-> only(['usr_prf_color','usr_prf_nav','usr_prf_scroll']);
$user->update($data);
$theme = DB::table('users')
->select('usr_prf_color','usr_prf_nav','usr_prf_scroll')
->where('id', $user->id)
->get();
return view('profile.index',compact('theme'));
}
Here's my view code:
<form action="{{ route('profile.themeUpdate', auth()->user()->id) }}" method="POST">
#csrf
#method('PUT')
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Color</label>
<select name="usr_prf_color" class="form-control">
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
</div>
<div class="form-group">
<label>Navigation</label>
<select name="usr_prf_nav" class="form-control">
<option value="horizontal">Horizontal</option>
<option value="vertical">Vertical</option>
<option value="hidden">Hidden</option>
</select>
</div>
<div class="form-group">
<label>Scroll</label>
<select name="usr_prf_scroll" class="form-control">
<option value="scrollable">Scrollable</option>
<option value="non-scrollable">Non-Scrollable</option>
</select>
</div>
</div>
</div>
<button type='submit' class="btn btn-primary">Update</button>
</form>
Here's my route:
Route::put('profile-theme', 'UserProfileController#themeUpdate')->name('profile.themeUpdate');
Here's my model:
class User extends Authenticatable
{
use Notifiable;
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'status', 'privilege' ,'password', 'usr_prf_color', 'usr_prf_nav', 'usr_prf_scroll',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
There's no error when I run this coding, but the data does not stored into database. Can anyone help me to solve this problem. Thank you in advanced.

in your view add id in an input hidden,
in your controller add
User::where('id', $request->input('id'))->update($data);

Try following code:It should work.
$validator = \Validator::make($request->all(),[
'usr_prf_color' =>'required',
'usr_prf_nav' => 'required',
'usr_prf_scroll' => 'required'
]);
if ($validator->fails()) {
return redirect('profile.index')
->withErrors($validator)
->withInput();
}
$user = User::where('id', $request->input('id');
$user->update($request->only(['usr_prf_color','usr_prf_nav','usr_prf_scroll']));
$theme = $user->refresh();
return view('profile.index',compact('theme'));

Related

Why registerController is not inserting data to database in laravel

I am new to laravel. I want to insert users data to database using registerController in laravel.
What I have tried is:
register.blade.php
#extends('adminlte::auth.auth-page', ['auth_type' => 'register'])
#php( $login_url = View::getSection('login_url') ?? config('adminlte.login_url', 'login') )
#php( $register_url = View::getSection('register_url') ?? config('adminlte.register_url', 'register') )
#if (config('adminlte.use_route_url', false))
#php( $login_url = $login_url ? route($login_url) : '' )
#php( $register_url = $register_url ? route($register_url) : '' )
#else
#php( $login_url = $login_url ? url($login_url) : '' )
#php( $register_url = $register_url ? url($register_url) : '' )
#endif
#section('auth_header', __('adminlte::adminlte.register_message'))
#section('auth_body')
<?php $res= DB::table('states')->orderBy('name','asc')->get();
?>
<form method="POST" action="{{ route('register_user') }}" class="registerForm">
#csrf
<div class="row">
<div class="col-md-6">
{{-- First Name field --}}
<div class="col-md-6">
<div class="input-group form-group">
<input type="text" class="form-control" placeholder="First Name *" name="first_name" value="" required>
</div>
</div>
</div>
<div class="col-md-6">
<div class="input-group form-group">
<input type="text" class="form-control" placeholder="Last Name *" name="last_name" value="" required>
</div>
</div>
<div class="col-md-6">
<div class="input-group form-group">
<input type="email" class="form-control" name="email" value="" placeholder="Email *" required>
</div>
</div>
<div class="col-md-6">
<div class="input-group form-group">
<input type="text" class="form-control phoneMask" placeholder="Phone *" name="phone" value="" required>
</div>
</div>
<div class="row">
<div class="col-md-3 col-xs-offset-4 submit_btn">
{{-- Register button --}}
<button type="submit" class="btn btn-block {{ config('adminlte.classes_auth_btn', 'btn-flat btn-primary') }}">
<span class="fas fa-user-plus"></span>
{{ __('adminlte::adminlte.register') }}
</button>
</div>
</div>
</div>
</form>
#stop
#section('auth_footer')
<p class="my-0">
<a href="{{ route('login') }}">
{{ __('adminlte::adminlte.i_already_have_a_membership') }}
</a>
</p>
#stop
RegisterController.php
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;
use Auth;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'first_name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users']
//'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
/*protected function create(array $data)
{
/*return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
dd($data);
$user= User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'mobile' => $data['phone']
]);
// dd($data['password'], $user->password);
return $user;
}*/
public function registerUsers(Request $request)
{
$first_name=$request->input('first_name');
$last_name=$request->input('last_name');
$email=$request->input('email');
$phone=$request->input('phone');
dd($request);
DB::insert('insert into users(first_name,last_name,email,phone)values(?,?,?,?)',[$first_name,$last_name,$email,$phone]);
}
}
web.php
Route::get('/', function () {
return view('auth.login');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::post('/register_user', 'Auth\RegisterController#registerUsers')->name('register_user');
Model
class User extends Authenticatable implements AuditableContract
{
use HasApiTokens, Notifiable;
use SoftDeletes;
use Auditable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
protected $fillable = ['first_name', 'last_name','email','phone','device_token','password','approved','added_by','removed','removed_by','deleted_at'];
}
When I try to submit this form, it is not inserting data to database and is showing HTTP error 500 and couldn't handle request.
What my form looks like
How to fix and insert data to database.
Try to add the cross-fire request forgery to your form. Generally I get this error when I forget it.
Add it like that in your view:
<?php $res= DB::table('states')->orderBy('name','asc')->get(); ?>
<form method="POST" action="{{ route('register_user') }}" class="registerForm">
#csrf
<div class="row">
<div class="col-md-6">
{{-- First Name field --}}
Route
Route::post('/test', 'Auth\RegisterController#test')->name('test');
Auth\RegisterController
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
.
.
.
public function test ( Request $request){
$rules = array(
'first_name' => 'required', 'string', 'max:255',
// add validation rules here
);
$validator = Validator::make($request->all(), $rules);
if ($validator->passes()) {
$user = new User();
$user->name = $request->input('first_name');
//copy above line and add remaining fields.
$user->save();
return redirect()->back()->with(array('message' => 'user added.'));
} else {
return redirect()->back()->withErrors($validator)->withInput();
}
}
follow these steps
make sure your request received by the desired route
make sure you have passed validation
then input data like this
DB::table('post')->insert([
DB::table('posts')->insert([
'name_name' => \request()->name,
'last_name' => \request()->last_name,
'email' => \request()->email,
'phone' => \request()->phone,
]);

How do I list my foreign keys in my customer registration view with Laravel?

Is the relationship working in the bank, but I can't show it in my registration view?
Usuario.php
class Usuario extends Model
{
protected $fillable = [
'company',
'name',
'document',
'phone',
'email'
];
public function empresa()
{
return $this->belongsTo('App\Empresa');
}}
Empresa.php
class Empresa extends Model
{
protected $fillable = [
'name',
'uf',
'cnpj'
];
public function usuarios()
{
return $this->hasMany('App\Usuario');
}}
form.blade.php
#foreach($usuarios as $u)
<option value="{{ $u->company_id->name }}">{{ $u->company_id->name }}</option>
#endforeach
UsuarioController.php
class UsuariosController extends Controller
{
public function new(){
$usuarios = Usuario::get();
return view('usuarios.form', ['usuarios' => $usuarios]);
}
enter image description here
please change your empresa() method in Usuario class.
public function empresa()
{
return $this->belongsTo('App\Empresa', 'company');
}
and blade file will be changes like this.
#foreach($usuarios as $u)
<option value="{{ $u->empresa->name }}">{{ $u->empresa->name }}</option>
#endforeach
form.blade.php
#csrf
<div class="form-group">
<label for="exampleInputEmail1">Empresa:</label>
<select name="company" class="form-control">
#foreach($usuarios as $u)
<option value="{{ $u->empresa->name }}">{{ $u->empresa->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Nome:</label>
<input type="text" name="name" class="form-control">
</div>
UsuarioController.
class UsuariosController extends Controller
{
public function index(){
$usuarios = Usuario::get();
return view('usuarios.list', ['usuarios' => $usuarios]);
}
public function new(){
$usuarios = Usuario::get();
return view('usuarios.form', ['usuarios' => $usuarios]);
}
public function adicionar( Request $request ){
$usuario = new Usuario;
$usuarios = Usuario::get();
$usuario = $usuario->create( $request->all() );
return Redirect::to('/usuarios', ['usuarios' => $usuarios]);
}
public function editar( $id ){
$usuario = Usuario::findOrFail( $id );
return view('usuarios.form', ['usuario' => $usuario]);

Laravel - multiple selection and saving to database

I have this small project for car posts. I make my post so everything is working properly, but now i need to have multiple selections. So this is my PostsController:
...
/**
* 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',
'brand' => 'required',
'model' => 'required',
'age' => 'required',
'cc' => 'required',
'hp' => 'required',
'body' => 'required',
'fuel' => 'required',
'safety' => 'required'
]);
$post = new Post;
$post->title = $request->input('title');
$post->brand = $request->input('brand');
$post->model = $request->input('model');
$post->age = $request->input('age');
$post->cc = $request->input('cc');
$post->hp = $request->input('hp');
$post->body = $request->input('body');
$post->fuel = $request->input('fuel');
$post->safety = $request->input('safety');
$post->save();
return redirect('/home')->with('success', 'Your post is posted!');
}
...
And now this is my createpost.blade.php :
...
<div class="column">
<label for="safety">Safety:</label></br>
<select class="form-control" name="safety">
<option value="" disabled selected>Select your option</option>
<option value="diesel">ABS</option>
<option value="gasoline">ESP</option>
<option value="electric">CHILD LOCK</option>
<option value="electric">AirBAG</option>
</select>
</div>
...
How can i make this select input for multiple selection and all of the selections need to save into my database? I have my Post.php model:
...
class Post extends Model
{
protected $table = 'posts';
protected $primaryKey = 'id';
}
Please help if anybody have solutions for this? Or some tutorials or any help similar!
Try some multi select libraries
Select2 is one among them
Use array in your blade.php file and also use multiple
<select class="form-control" name="safety[]" multiple>
In controller
$post->safety = implode(',', $request->input('safety'));
You can use checkbox in blade file
$("input:checkbox").click(function(e){
console.log(e.target.checked ? e.target.value : e.target.value+' is unchecked')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<label for="safety">Safety:</label></br>
<input type="checkbox" value="ABS" name="safety[]" />ABS
<input type="checkbox" value="ESP" name="safety[]" />ESP
<input type="checkbox" value="CHILD LOCK" name="safety[]" />CHILD LOCK
<input type="checkbox" value="AirBAG" name="safety[]" />AirBAG
</div>
And retrieve your data from $request in controller as follows:
$request->input('safety') // return an array with all checked value, e.g: ['ABS','ESP']
add multiple attribute in select tag
change
<select class="form-control" name="safety[]">
to
<select class="form-control" name="safety[]" multiple>
This will let you select multiple options.
User will have to use control/cmd key to select multiple options

Laravel 5.8 PDF upload

for my website I need a form which includes a file upload for PDF files, but I'm new to these and don't really know how to do it.
This is what I got so far, but keep getting:
"Too few arguments to function App\Http\Controllers\FileController::create(), 0 passed and exactly 1 expected"
Controller:
<?php
namespace App\Http\Controllers;
use App\User;
use App\Payment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class FileController extends Controller
{
public function index(){
$users = User::all();
return view('fileupload.create', compact('users'));
}
protected function create(array $data)
{
$request = app('request');
if($request->hasfile('file')){
$file = $request->file('file');
$filename = $file['filename']->getClientOriginalExtension();
Storage::make($file)->save( public_path('/storage/loonstrookjes/' . $filename) );
dd($filename);
}
return Payment::create([
'file_name' => $filename,
'file_path' => '/storage/loonstrookjes/',
'user_id' => $data['employee'],
]);
return route('fileupload.create');
}
}
Model User:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Kyslik\ColumnSortable\Sortable;
class User extends Authenticatable
{
use Notifiable;
use Sortable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $table = 'users';
protected $fillable = [
'username', 'first_name', 'last_name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Model Payment:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Payment extends Model
{
protected $table = 'payment_list';
protected $fillable = [
'user_id', 'file_name', 'file_path'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'id', 'file_name', 'file_path'
];
}
View:
#extends('layouts.master')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Loonstrook uploaden') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('create') }}" enctype="multipart/form-data">
#csrf
<div class="form-group row">
<label for="filename" class="col-md-4 col-form-label text-md-right">{{ __('Bestandsnaam') }}</label>
<div class="col-md-6">
<input id="filename" type="text" class="form-control{{ $errors->has('filename') ? ' is-invalid' : '' }}" name="filename" value="{{ old('filename') }}" required autofocus>
#if ($errors->has('filename'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('filename') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="file" class="col-md-4 col-form-label text-md-right">{{ __('Bestand') }}</label>
<div class="col-md-6">
<input id="file" type="file" class="form-control" name="file">
</div>
</div>
<div class="form-group row">
<label for="usertype" class="col-md-4 col-form-label text-md-right">{{ __('Werknemer:') }}</label>
<div class="col-md-6">
<select class="form-control" name="type">
#foreach($users as $user)
<option value="{{$user->id}}">{{$user->first_name}} {{$user->last_name}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Uploaden') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
These are my routes:
Route::get('/create', 'FileController#index')->name('create');
Route::post('/create', 'FileController#create');
I hope someone can help me find out what's wrong or a better way to do this. Thank you in advance!!
EDIT:
Your answers have helped me quite a bit, but now I'm facing another issue...
The controller now looks like this:
<?php
namespace App\Http\Controllers;
use App\User;
use App\Payment;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\File\UploadedFile;
UploadedFile::getMaxFilesize();
class FileController extends Controller
{
public function index(){
$users = User::all();
return view('fileupload.create', compact('users'));
}
protected function validator(array $data)
{
return Validator::make($data, [
'filename' => ['required', 'string', 'max:255'],
'file' => ['required', 'file'],
'user_id' => ['required'],
]);
}
protected function create(Request $request)
{
$request = app('request');
if($request->hasfile('file')){
$file = $request->file('file');
$filename = $request->input('filename');
$file = $filename . '.' . $file->getClientOriginalExtension();
$file_path = storage_path('/loonstrookjes');
Storage::disk('local')->putFile($file_path, new File($request->file), $file);
//$path = $request->file('file')->store( storage_path('/storage/loonstrookjes/'));
//$path = Storage::putFile(storage_path('/loonstrookjes/'), $filename);
//dd($upload);
//return $put;
}
return Payment::create([
'file_name' => $filename,
'file_path' => '/storage/loonstrookjes/',
'user_id' => $request['user'],
]);
return route('fileupload.create');
}
}
But I'm getting a new error, this time it's:
Call to undefined method Illuminate\Support\Facades\File::hashName()
Any ideas??
Your problem is you have a parameter in your method create(array $data), but you are posting the form using only {{ route('create') }}. Here you are calling the method by this route without passing the required parameter as you defined it.
Basically, a form post method can accept the requested values by this
protected function create(Request $request)
Because you already used Request as a trait.
So, by this, you can get the requested field value from your form. And you don't have to use $request = app('request'); since you already have it on the parameter variable $request.
In case you want to know
Variables are passed from frontend (view)
to the backend (route) by using {{ route('update', $the_variable) }}.
By this, you can have $the_variable after the last / of your route.
Hope this helps.
Route:
Route::resource('File','FileController');
Controller changes:
public function store(Request $request)
{
if($request->hasfile('file')){
$file = $request->file('file');
$filename = $file['filename']->getClientOriginalExtension();
Storage::make($file)->save( public_path('/storage/loonstrookjes/' . $filename) );
}
return Payment::create([
'file_name' => $filename,
'file_path' => '/storage/loonstrookjes/',
'user_id' => $request->type
]);
return route('fileupload.create');
}
}
View Changes:
form action="{{ route('File.store') }}"

No query results for model [User] | laravel

I'm a newbie to Laravel so I'm not yet familiar with the errors it's returning, I hope someone can help me with this.
So I created a simple app with registration form and a login form and the registered user can post whatever he/she wants but I'm getting this error
This is the form where the user can post:
#section('content')
<section class="header">
<ul>
<li></li>
<li>Back to Profile</li>
</ul>
</section>
<div class="newpost">
<h3>What new today?</h3><br>
<form action="{{URL::route('createPost')}}" method="post" autocomplete="off">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" name="title" placeholder="Title..." required>
</div>
<div class="form-group">
<label for="content">Write Report</label>
<textarea class="form-control" name="content" id="content" placeholder="Write Here..." rows="10"></textarea>
</div>
<button type="submit" class="btn2">Publish</button>
</form>
</div>
#stop
This is the route:
Route::get('/Newpost', array(
'uses' => 'LoginUsersController#newPost',
'as' => 'newPost'
));
Route::post('/CreatePost/{id}', array(
'uses' => 'LoginUsersController#createPost',
'as' => 'createPost'
));
and the controller
public function createPost($id)
{
$users = User::findOrFail($id);
$post = array(
'title' => Input::get('title'),
'content' => Input::get('content')
);
$posts = new Post($post);
$user->post()->save($post);
dd($post);
}
and the User model where I'm guessing is causing the error.
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
protected $fillable = array('email', 'password');
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
public function Post()
{
return $this->hasMany('Post', 'user_id');
}
}
Can someone please explain to me why I'm getting this error? Thanks
This error is caused because findOrFail can't find anything. So it fails.
If your route depends on the users id. You actually have to pass it along when creating your form:
<form action="{{URL::route('createPost', Auth::id())}}" method="post" autocomplete="off">
(Auth::id() retrieves the id of the current logged in user)
However instead, I suggest that you remove the user id from the createPost route and work with the currently logged in user directly in the controller:
Route::post('/CreatePost', array(
'uses' => 'LoginUsersController#createPost',
'as' => 'createPost'
));
And then:
public function createPost()
{
$user = Auth::user();
$post = array(
'title' => Input::get('title'),
'content' => Input::get('content')
);
$posts = new Post($post);
$user->post()->save($post);
dd($post);
}

Categories