Need help in creating a user in Laravel with roles - php

I followed a nice tutorial on how to create roles and how to use gates with Laravel.
I can seed users with roles and edit them, but I would like to be able to create a user and give him/her one or more roles and I don't know where to start (I'm not a pro, but I need to finish this app).
Here's all the code I can show you so far :
Users Controller :
public function edit(User $user, $id)
{
$user = User::findOrFail($id);
$roles = Role::all();
return view('admin.users.edit',compact('user', 'roles'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\User $user
* #return \Illuminate\Http\Response
*/
public function update(Request $request, User $user, $id)
{
$user = User::findOrFail($id);
$user->roles()->sync($request->roles);
$user->name = $request->name;
$user->email = $request->email;
$user->save();
return redirect()->route('admin.utilisateurs.index');
}
Roles Table :
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
Pivot Table :
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->id();
$table->BigInteger('role_id')->unsigned()->onDelete('cascade');
$table->BigInteger('user_id')->unsigned()->onDelete('cascade');
$table->timestamps();
});
}
Edit blade file with checkboxes :
<div class="block-content">
<div class="form-group">
#foreach ($roles as $role)
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" name="roles[]"
value="{{ $role->id }}" id="{{ $role->id }}"
#if ($user->roles->pluck('id')->contains($role->id)) checked #endif>
<label class="" for="{{ $role->id }}">{{ $role->name }}</label>
</div>
#endforeach
</div>
</div>
The thing is that I don't really know how to write my code on the Create Blade File.
Here's the create method on the controller (not sure if it's correct or not) :
public function store(Request $request, User $user)
{
$user = new User();
$user->roles()->sync($request->roles);
$user->name = $request->name;
$user->email = $request->email;
$user->save();
return redirect()->route('admin.utilisateurs.index')->with('success','Utilisateur ajouté');
}
Thanks for reading this long message!
Peace

on create blade it's almost as same as edit blade. you just need not to check for existing roles.
//rest of the form first like user name and email
<div class="block-content">
<div class="form-group">
#foreach ($roles as $role)
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" name="roles[]" value="{{ $role->id }}" id="{{ $role->id }}">
<label class="" for="{{ $role->id }}">{{ $role->name }}</label>
</div>
#endforeach
</div>
</div>
and then in controller instead of sync just use attach
public function store(Request $request)
{
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->save();
$user->roles()->attach($request->roles);
return redirect()->route('admin.utilisateurs.index')->with('success','Utilisateurajouté');
}
look i have removed model binding in store function. it's not necessary in here. and attached roles after saving the user. docs on attach and sync in here.

Related

QLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value laravel

I cannot store the company that my client belongs to. The company is a foreign key and when I click register customer I get an error:
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: 'Tim' for column customerlist.customers.company at row 1 (SQL: insert into customers (company, name, document, phone, email, updated_at, created_at) values (Tim, Felix Botta, 04919407939, +55.41984081085,felix.botta#gmail.com, 2021-02-14 20:55:15, 2021-02-14 20:55:15))
CustomerController
class CustomersController extends Controller
{
public function index(){
$customers = Customer::get();
return view('customers.list', ['customers' => $customers]);
}
public function new(){
$companies = Company::orderBy('id', 'desc')->get();
return view('customers.form', ['companies' => $companies]);
}
public function add( Request $request ){
$customers = new Customer;
$customers = $customers->create( $request->all() );
return Redirect::to('/customers');
}
public function edit( $id ){
$customers = Customer::findOrFail( $id );
return view('customers.form', ['customers' => $customers]);
}
public function update( $id, Request $request ){
$customers = Customer::findOrFail( $id );
$customers->update( $request->all() );
return Redirect::to('/customers');
}
public function delete( $id ){
$customers = Customer::findOrFail( $id );
$customers->delete();
return Redirect::to('/customers');
}}
form.blade
<form action="{{ url('customers/add') }}" method="post">
#csrf
<div class="form-group">
<label for="">Empresa:</label>
<select name="company" class="form-control">
#foreach($companies as $company)
<option value="{{ $company->name }}">{{ $company->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Nome:</label>
<input type="text" name="name" class="form-control">
</div>
<div class="form-group">
<label for="exampleInputEmail1">CPF / CNPJ:</label>
<input type="text" name="document" class="form-control">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Telefone:</label>
<input type="text" name="phone" class="form-control">
</div>
<div class="form-group">
<label for="exampleInputEmail1">E-mail:</label>
<input type="email" name="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
</div>
<button type="submit" class="btn btn-primary">Cadastrar</button>
</form>
#endif
</div>
class CreateCustomersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('customers', function (Blueprint $table) {
$table->id();
$table->string('name', 256);
$table->string('document', 256);
$table->string('phone', 128);
$table->string('email', 128);
$table->foreignId('company')->constrained('companies');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('customers');
}}
According to the migration the company column is integer and foreign key that points to companies table and according to error you are passing string value Tim for company column. So in blade view change
<option value="{{ $company->name }}">{{ $company->name }}</option>
to
<option value="{{ $company->id }}">{{ $company->name }}</option>

Laravel 7: Cannot update record in users table

I've searched but couldn't find a working solution. I simply cannot update a specific field (status) in users table. I've added two additional fields in Laravel's auth users original table.
Here is the migration code:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->unsignedBigInteger('role_id');
$table->integer('status')->default(0);
$table->foreign('role_id')->references('id')->on('roles');
});
}
I've also added fillable:
protected $fillable = ['name', 'email', 'password', 'role_id', 'status'];
Now the issue is I cannot update "status" field and the operation doesn't return any issue. I already have tried it with different approaches. Have a look at the code and guide me. TIA.
public function update(Request $request, $id)
{
$validatedData = $request->validate([]);
// APPROACH # 1
$user = User::find($id);
$user->status = $request->status;
$user->save();
// APPROACH # 2
$user = User::find($id);
$user->update([
'status' => $request->status,
]);
// APPROACH # 3
User::findOrFail($id)->update($request->all());
}
Form:
<form action="{{ url('/admin/user') }}/{{ $editRecord[0]->id }}" method="POST" enctype="multipart/form-data">
#method('PUT')
#csrf
<select id="status" name="status" class="form-control">
<option value="1" #if($editRecord[0]->status == 1) selected #endif>Active</option>
<option value="0" #if($editRecord[0]->status == 0) selected #endif>In-Active</option>
</select>
</form>
Finally the route:
Route::put('/admin/user/{id}', 'Admin\PortalController#update');
Then code is working fine may be you forget to redirect back with success message. you should try below -
if($user->save()){
return redirect()->back()->with('message', 'updated successfully');
} else {
return redirect()->back()->with('error', 'something went wrong');
}
Then in blade file -
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
#endif
#if(session()->has('error'))
<div class="alert alert-danger">
{{ session()->get('error') }}
</div>
#endif

How to insert data from a show page of one model to a pivot table in laravel

I am trying to fill a pivot table with the user_id of the current user and event_id of the event that the user is viewing. But on clicking submit the page shows The page has expired due to inactivity. Please refresh and try again. Here is my code:
EventController.php
public function index()
{
$events = DB::table('events')->get();
return view('events.index', ['events'=>$events]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('events.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$event = new Event;
$event->title = $request->eventTitle;
$event->location = $request->eventLocation;
$event->date = $request->eventDate;
$event->time = $request->eventTime;
$event->save();
Session::flash('success', 'Event created successfully');
return redirect()->route('events.create');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$event = Event::find($id);
return view('events.show', ['event'=>$event]);
}
EventsUsersController.php
public function store(Request $request)
{
$event_id = $request->id;
$user_id = $request->Auth::user()->id;
DB::table('event_user')->insert([
['event_id' => $event_id],
['user_id' => $user_id]
]);
}
and the show page from where I want to insert data into the pivot table
#extends('layouts.app')
#section('content')
<div class="container">
<h1>{{$event->title}}</h1>
<p>Date: {{$event->date}}</p>
<p>Time: {{$event->time}}</p>
<p>Location: {{$event->location}}</p>
#if(Auth::check())
<form method="POST" action="{{ route('eventsusers.store') }}">
{{ csrf_field() }}
<input type="hidden" name="event_id" value="{{ $event->id }}">
<input type="hidden" name="user_id" value="{{ Auth::user()->id }}">
<button type="submit" class="btn btn-success">Register</button>
</form>
#endif
</div>
#endsection
My migration file for user_event table:
public function up()
{
Schema::create('event_user', function (Blueprint $table) {
$table->integer('event_id');
$table->integer('user_id');
$table->timestamps();
$table->primary(['event_id', 'user_id']);
});
}
I am new to laravel. So please be gentle. :)
csrf token can create this type of problem. There are several ways to solve it.
Add {{ csrf_field() }} inside your form like below code & check what happens.
{{ csrf_field() }}
Register
You can add a hidden field like this <input type="hidden" name="_token" value="{{ csrf_token() }}">
You can update VerifyCsrfToken middleware using this approach
protected $except = [
'your/route'
];

Laravel - Edit role user by role_name

I have made an edit page for my users and everything works except changing the role. I have made a select menu which displays all the roles through a foreach loop. And it displays the current role of the user like this:
<div class="form-group row">
<div class="col-md-4">
<label for="Datum">Rol:</label>
</div>
<div class="col-md-8">
<select class="form-control" id="Datum" name="role">
<option selected>{{ $user->role->role_name }}</option>
#foreach($roles as $role)
<option>{{ $role->role_name }}</option>
#endforeach
</select>
</div>
</div>
I want to be able to change the role by the role_name instead of ID. I honestly don't know where to look. How can I achieve this?
The controller that the form goes through looks like this:
public function updateUser(Request $request, $id)
{
$user = User::find($id);
$user->update($request->all());
$user->save();
return back()->with('flash', 'Account is geupdate');
}
In the database, a user has a role_id and in the role table, it has all the roles. So the relations are: User has a Role, Role has many users. These relations are set in the models. So {{ $user->role->role_name }} works just fine.
Thanks in advance!
Assume role_name is unique. In your post method you can do the following-
public function updateUser(Request $request, $id)
{
$role = Role::where('role_name','=',$request->input('role_name'))->first();
$user = User::find($id);
$user->role_id = $role->id;
$user->save();
return back()->with('flash', 'Account is geupdate');
}
As per your comment, add this on your user model-
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
Hope it helps :)

Undefined variable:user laravel

I keep on getting this error whenever I try to enter the upload page.
Can anybody help?
I have already done the compact part to make sure that the variable is being passed to the view and also my route should be ok I think.
I tried using dd but all it does is keep on showing me the error
Error: Undefined variable: user (View: C:\xampp\htdocs\Evaluation\resources\views\upload.blade.php)
Here are my codes:
upload.blade.php
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{$user->id}}">
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input type="file" name="file">
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
UploadController:
public function upload(){
return view(‘upload’);
}
public function store(Request $request,$id){
$this->validate($request, [
'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
var_dump('has file '.$request->hasFile('file'));
if ($request->hasFile('file')) {
$image = $request->file('file');
$name = $image->getClientOriginalName();
$size = $image->getClientSize();
$id = $request->user_id;
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$Image = new Image;
$Image->name = $name;
$Image->size = $size;
// $Image->user_id = $id;
//$Image->save();
$user->find($id);
dd($user);
$user->Images()->save($Image);
}
return redirect('/home');
}
public function test(){
$user = user_information::where('id')->get();
return view('upload', compact('user'));
}
Route: (this are my route)
Route::get('/UploadUser/upload','UploadController#upload’);
Route::post('/UploadUser','UploadController#store');
Route::post('/UploadUser/upload', 'UploadController#test');
Another question: I keep on getting this error when i try to upload a file, so what should I do?
Here is the error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails (form.images,
CONSTRAINT images_user_id_foreign FOREIGN KEY (user_id) REFERENCES
usere_information (id)) (SQL: insert into images (name,
size, user_id, updated_at, created_at) values (download.png,
4247, 1, 2017-10-25 08:54:57, 2017-10-25 08:54:57))
Image model:
class Image extends Model
{
protected $fillable = array('name','size','user_id');
public function user_informations() {
return $this->belongsTo('App\user_information', 'user_id', 'id');
}
}
Images table:
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('size');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('user_informations');
$table->timestamps();
});
User_information table:
Schema::create('user_informations', function (Blueprint $table) {
$table->increments('id');
$table->engine = 'InnoDB';
$table->binary('signature');
$table->String('Name');
$table->timestamps();
});
User_information model:
class user_information extends Eloquent
{
protected $fillable = array('signature', 'Name');
protected $table = 'user_informations';
protected $primaryKey = 'id';
public function Images() {
return $this->hasOne('App\Image','user_id');
}
}
How to get the image?
Here is the view folder:
#foreach ($data as $object)
<b>Name: </b>{{ $object->Name }}<br><br>
Edit<br>
#foreach ($data3 as $currentUser)
<img src="{{ asset('public/images/' . $currentUser->Image->name ) }}">
#endforeach
#if($data3->count())
#foreach($data3 as $currentUser)
<a href="{!! route('user.upload.image', ['id'=>$currentUser->user_id]) !!}">
<button class="btn btn-primary"><i class ="fa fa-plus"></i>Upload Images</button>
</a>
#endforeach
#else
<a href="{!! route('user.upload.image', ['id'=>$object->id]) !!}">
<button class="btn btn-primary"><i class ="fa fa-plus"></i>Upload Images</button>
#endif
#endforeach
HomeController:
public function getInfo($id) {
$data = user_information::where('id',$id)->get();
$data3=Image::where('user_id',$id)->get();
return view('test',compact('data','data3'));
Because you didn't pass the user to your upload view, try to pass it like this :
public function upload(){
$id = 1 //The wanted user or if the user is authenticated use Auth::id()
$user = User::find($id);
return view('upload')->withUser($user);
}
Or if the user is authenticated use Auth in the view :
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{auth()->id()}}">
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input type="file" name="file">
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
For the second problem it's because in the route you have
Route::post('/UploadUser','UploadController#store');
and the your store method signature is
public function store(Request $request,$id){
The $id parameter that did the problem because it's not defined in the route so simply remove it from the method signatre
public function store(Request $request){
$this->validate($request, [
'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($request->hasFile('file')) {
$image = $request->file('file');
$name = $image->getClientOriginalName();
$size = $image->getClientSize();
$id = $request->user_id; // here id is declared no need for the parameter
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$Image = new Image;
$Image->name = $name;
$Image->size = $size;
$Image->user_id = $id;
$Image->save();
}
return redirect('/home');
}
For the third case you have to change the routes from :
Route::get('/UploadUser/upload','UploadController#upload’);
to
Route::get('/UploadUser/{user}/upload','UploadController#upload’)->name('user.upload.image');
And in the view add the id in the upload button url maybe like this :
{!! route('user.upload.image', ['user'=>$currentUser->id]) !!}
Then in the upload method :
public function upload(user_information $user){ // route model binding here
// dd($user); //for testing only :)
return view('upload')->withUser($user);
}
In the view change
<input type="hidden" name="user_id" value="{{auth()->id()}}">
To
<input type="hidden" name="user_id" value="{{$user->id()}}">
And you are good to go ;)
#foreach ($data as $currentUser)
<b>Name: </b>{{ $currentUser->Name }}<br><br>
Edit<br>
#if($currentUser->Image)
<img src="{{ asset('public/images/' . $currentUser->Image->name ) }}">
#endif
<a href="{!! route('user.upload.image', ['id'=>$currentUser->id]) !!}">
#endforeach
You have miss to pass id in your where condition,
public function test(){
$user = user_information::where('id',$id)->first();
return view('create1', compact('user'));
}
and you have to pass your user data into this,
public function upload(){
$user = user_information::where('id',$id)->first();
return view(‘upload’,compact('user'));
}
Hope it helps,
On your upload function, you have to pass the user variable because you use the $user in the view. So the controller will be
public function upload() {
$user = Auth::user();
return view('upload', compact('user'));
}
do not forget to change the $user based on your need.
You have to pass an $id variable into your test() method. Then please comment below what's the error next so I can follow you through.
Update
Since you don't want to pass an id. You can use:
public function test(){
$u = Auth::user();
$user = user_information::where('id', $u->id)->get();
return view('upload', compact('user'));
}
OR
Try to use first() instead of get().
More option:
I have noticed, you're using the upload() method here, why not passing the $user there? like so:
public function upload(){
$user = Auth::user();
return view(‘upload’, compact('user'));
}

Categories