Laravel: Trouble with update db after click button - php

I have problem: I build an app and I have 2 tables in my db: habits and users. The User has a field called points and after click a button 'Add point' I want to increment that value. I added a method in HabitsController called addPoints and button in a view, but I get an error message: MethodNotAllowedHttpException No message. There is my code.
HabitsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Habit;
use App\User;
use DB;
use App\Quotation;
class HabitsController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//store in $habits all posts of current user
$habits = DB::table('habits')->where('user_id', auth()->id())->get();
return view('habits.index')->with('habits', $habits);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('habits.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',
'description'=>'required',
'difficulty'=>'required'
]);
$habit = new Habit;
$habit->name = $request->input('name');
$habit->description = $request->input('description');
$habit->difficulty = $request->input('difficulty');
$habit->NumberOfCompleted = 0;
$habit->user_id = auth()->user()->id;
$habit->save();
return redirect('/habits')->with('success', 'Habit created');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$single = Habit::find($id);
return view('habits.show')->with('single', $single);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$single = Habit::find($id);
return view('habits.edit')->with('single', $single);
}
/**
* 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, [
'name'=>'required',
'description'=>'required',
'difficulty'=>'required'
]);
$habit = Habit::find($id);
$habit->name = $request->input('name');
$habit->description = $request->input('description');
$habit->difficulty = $request->input('difficulty');
$habit->NumberOfCompleted = 0;
$habit->save();
return redirect('/habits')->with('success', 'Habit created');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$single = Habit::find($id);
$single->delete();
return redirect('/habits')->with('success', 'Habit deleted');
}
public function addPoint(Request $request, $id)
{
$habit = User::find($id);
$habit->points += 1;
$habit->save();
return redirect('/habits')->with('success', 'Habit created');
}
}
show.blade.php
#extends('layouts/app')
#section('content')
<div class="row single">
<div class="col-sm-8 col-sm-offset-2 showSingleHabit">
<h2>{{$single->name}}</h2>
<p>{{$single->description}}</p>
<p>{{$single->difficulty}}</p>
<p>{{$single->NumberOfCompleted}}</p>
Edit
{!!Form::open(['action' => ['HabitsController#destroy', $single->id], 'method' => 'POST'])!!}
{{Form::hidden('_method', 'DELETE')}}
{{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
{!!Form::close()!!}
{!!Form::open(['action' => ['HabitsController#update', $single->id], 'method' => 'POST'])!!}
{{Form::hidden('_method', 'POST')}}
{{Form::submit('Add point', ['class' => 'btn btn-primary'])}}
{!!Form::close()!!}
</div>
</div>
#endsection
routes/web.php
Route::get('/', 'PagesController#index');
Route::get('/about', 'PagesController#about');
Route::resource('habits', 'HabitsController');
Auth::routes();
Route::get('/dashboard', 'DashboardController#index');
I will be grateful for any help. :)

Change
{{Form::hidden('_method', 'POST')}}
To
{{Form::hidden('_method', 'PUT')}}

Related

Laravel foreach variable not working ($tickets is undefined)

Hello When I run page it tells me that:
ErrorException
Undefined variable: tickets (View: D:\xampp\htdocs\new-helpdesk\resources\views\tickets\index.blade.php)
http://localhost:8000/tickets
Hide solutions
$tickets is undefined
when I dd it works.
index.blade.php
#extends('layouts.ticket')
#section('content')
#if ($tickets)
**
**#foreach ($tickets as $ticket)
<div class="form-group">
{!! Form::label('company', 'Company:', ['class' => 'form-label fs-6 d-inline-block']) !!}
{!! Form::select('company', [' '=> 'Choose Company'], null,['class'=>'form-control']);!!}
</div>
#endforeach
#endif
#endsection
TicketsController
<?php
namespace App\Http\Controllers;
use App\Models\Companies;
use App\Models\Tickets;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class TicketsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
// $tickets = Tickets::with('companies')->get();
return view('tickets.index');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
// return view('tickets.create');
$tickets = Companies::all();
dd($tickets->toArray());
// return view('tickets.index', compact('tickets'))->with('tickets', $tickets);
return view('tickets.index')->with(['tickets' => $tickets]);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
$request->validate([
'ticket_title'=> 'required',
'description'=>'required'
]);
$query = DB::table('tickets')->insert([
'ticket_title'=>$request->input('ticket_title'),
'description'=>$request->input('description'),
]);
if($query){
return back()->with('success','Data have beeen inserted');
} else {
return back()->with('fail', 'Data not inserted');
}
}
/**
* Display the specified resource.
*
* #param \App\Models\Tickets $tickets
* #return \Illuminate\Http\Response
*/
public function show(Tickets $tickets)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Tickets $tickets
* #return \Illuminate\Http\Response
*/
public function edit(Tickets $tickets)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Tickets $tickets
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Tickets $tickets)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Tickets $tickets
* #return \Illuminate\Http\Response
*/
public function destroy(Tickets $tickets)
{
//
}
public function showcategory(){
// $companies = Companies::pluck('name', 'id');
// dd($companies);
}
}
web.php
Route::resource('/tickets', TicketsController::class);
Route::resource('/companies', CompaniesController::class);
Tickets Model
public function companys(){
return $this->belongsTo(Companies::class);
}
Companies Model
public function tickets(){
return $this->HasMany(Tickets::class);
}
How can I solve this problem?
I try to change it as layout
You have a little chaos in your return value, you either pass the collection in compact() or in with(). with() needs an array, so you will have to do one of the following:
return view('tickets.index', compact('tickets'));
//or
return view('tickets.index')->with(['tickets' => $tickets]);
=====EDIT
The /tickets route is calling your index() action. https://laravel.com/docs/9.x/controllers#actions-handled-by-resource-controller This action also returns the index.blade.php view, but you are not passing the tickets collection.
public function index()
{
$tickets = Tickets::with('companies')->get();
return view('tickets.index')->with(['tickets' => $tickets]);
}
As TimLewis pointed out, the #if($tickets) in your index.blade.php has no purpose and can be removed.

Create view in one controller and store data in other controller laravel

I'm new to Laravel and I'm trying to store a form. I created the view with the House controller but now I want to store the data in the view with the Booking controller. But when I click the button nothing happens.
My question is if it is possible to make a view with one controller and store it with another controller or maybe there is an other solution.
I also want to use the id of the house to store. How do I get that in the other controller as well?
Web Route
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| 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('/', [\App\Http\Controllers\HouseController::class, 'index']);
Route::get('house/{house}', [\App\Http\Controllers\HouseController::class, 'show']);
Route::post('house/{house}', [\App\Http\Controllers\BookingController::class, 'store']);
Route::get('rental', [\App\Http\Controllers\HouseController::class, 'getUserHouses']);
Route::get('rental/new', [\App\Http\Controllers\HouseController::class, 'create']);
Route::post('rental/new', [\App\Http\Controllers\HouseController::class, 'store']);
Route::get('rental/edit/{house}', [\App\Http\Controllers\HouseController::class, 'edit']);
Route::put('rental/edit/{house}', [\App\Http\Controllers\HouseController::class, 'update']);
Auth::routes();
Booking controller
<?php
namespace App\Http\Controllers;
use App\Models\Booking;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class BookingController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$newBooking = Booking::create([
'user_id' => Auth::id(),
'house_id' => $request->id,
'begin' => $request->begin,
'end' => $request->end,
'status' => 0
]);
return redirect('/');
}
/**
* Display the specified resource.
*
* #param \App\Models\Booking $booking
* #return \Illuminate\Http\Response
*/
public function show(Booking $booking)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Booking $booking
* #return \Illuminate\Http\Response
*/
public function edit(Booking $booking)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Booking $booking
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Booking $booking)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Booking $booking
* #return \Illuminate\Http\Response
*/
public function destroy(Booking $booking)
{
//
}
}
House controller
<?php
namespace App\Http\Controllers;
use App\Models\house;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Helper\Imageable;
use DB;
class HouseController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$houses = House::all();
return view('/home', [
'houses' => $houses
]);
}
/**
* Display a listing of the houses the owner has
*
* #return \Illuminate\Http\Response
*/
public function getUserHouses()
{
$houses = DB::table('houses')
->where('user_id', '=', Auth::id())
->get();
return view('/rental/rental', [
'houses' => $houses
]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('rental/new');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$path = Imageable::storeMedia($request);
$request->online === 'on' ? $online = 1 : $online = 0;
$newHouse = House::create([
'title' => $request->title,
'price_per_night' => $request->price,
'summary' => $request->summary,
'place' => $request->place,
'country' => $request->country,
'user_id' => Auth::id(),
'online' => $online,
'image' => $path,
]);
return redirect('rental');
}
/**
* Display the specified resource.
*
* #param \App\Models\house $house
* #return \Illuminate\Http\Response
*/
public function show(house $house)
{
return view(
'/house',
[
'house' => $house
]
);
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\house $house
* #return \Illuminate\Http\Response
*/
public function edit(house $house)
{
return view(
'rental/edit',
[
'house' => $house
]
);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\house $house
* #return \Illuminate\Http\Response
*/
public function update(Request $request, house $house)
{
$path = Imageable::storeMedia($request);
$request->online === 'on' ? $online = 1 : $online = 0;
$house->update([
'title' => $request->title,
'price_per_night' => $request->price,
'summary' => $request->summary,
'place' => $request->place,
'country' => $request->country,
'online' => $online,
'image' => $path,
]);
return redirect('rental/edit/' . $house->id);
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\house $house
* #return \Illuminate\Http\Response
*/
public function destroy(house $house)
{
//
}
}
View
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-12">
<h1 class="display-one ">{{ $house->title }}</h1>
<p class=".text-light">{{ $house->place }}, {{ $house->country }}</p>
</div>
</div>
<div class="row mt-5">
<div class="col-sm-6">
<img src="{{ asset("img/houses/$house->image") }}" alt="{{ $house->title }}" class="img-fluid" />
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="exampleFormControlSelect1">Kies een datum en reserveer direct</label>
<form method="POST" action="">
#csrf
<input type="date" name="begin">
<input type="date" name="end">
<div class="col-md-12 bg-light mt-3">
<button type="button" class="btn btn-warning ml-2">Vraag aan</button>
</div>
</form>
</div>
</div>
</div>
<div class="row mt-3">
<div class="col-sm-6">
<p class="display-one ">{{ $house->summary }}</p>
</div>
<div class="col-sm-6">
<h2 class="display-one ">Aangeboden door</h2>
<p>Prijs per nacht €{{ $house->price_per_night }}</p>
</div>
</div>
</div>
#endsection
First of all, nothing happens when you click the form submit button because it is currently type="button" and in order this button to play role of submission button it must be type="submit". You can do whatever you want with Laravel. If you want your form to hit another controller method you can simply specify that in your form tag. Like so:
Imagine this is a form inside a view that is rendered by HouseController
<form method="POST" action="{{ url('/save/from/booking/controller') }}">
// ....
</form>
And now on form submission inside a view that is rendered by HouseController, you will actually hit a route that is BookingController responsive for. And here is your route that is being hit by the form
Route::post('/save/from/booking/controller', [BookingController::class, 'store']);

How to render an uploaded image inside a view?

I am trying to get an image to upload and render when asked too.
I have successfully got the image upload working on my localhost, but once I push the code to the forge server, it breaks.
The image is uploaded however this is what I see once the post is created... See below.
I am not sure how to fix this issue.
Does anyone have any advice or suggestions on how to address this issue?
What I am doing wrong?
PostConroller
<?php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
class PostController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::all();
return view('post.index', compact('posts'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$post = new Post(); // What is this?
return view('post.create', compact ('post'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'body' => 'required',
]);
$post = Post::create([
'user_id' => Auth::id(),
'title' => $request->title,
'body' => $request->body
]);
$this->storeImage($post);
return redirect('/posts');
}
/**
* Display the specified resource.
*
* #param \App\Post $post
* #return \Illuminate\Http\Response
*/
public function show(Post $post)
{
return view('post.show', compact('post'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Post $post
* #return \Illuminate\Http\Response
*/
public function edit(Post $post)
{
return view('post.edit', compact('post'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Post $post
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Post $post)
{
$this->validatedRequest();
$post->update($request->except('image'));
$this->storeImage($post);
return redirect('/posts');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Post $post
* #return \Illuminate\Http\Response
*/
public function destroy(Post $post)
{
$post->delete();
return redirect('/posts');
}
private function validatedRequest()
{
return request()->validate([
'title' => 'required',
'body' => 'required',
'image' => 'sometimes|file|image|max:5000',
]);
}
private function storeImage($post)
{
if (request()->has('image')) {
$filename = Str::random(14).'.'.request()->image->getClientOriginalExtension();
$image = Image::make(request()->image)->fit(300, 300, null, 'top-left')->encode();
Storage::disk('public')->put("uploads/{$filename}", (string) $image);
$post->update([
'image' => "uploads/{$filename}"
]);
}
}
}
Form (show.blade.php)
#if($post->image)
<div class="row">
<div class="col-12">
<img src="{{ asset('storage/uploads/' . $post->image) }}" alt=""
class="img-thumbnail">
</div>
</div>
#endif
Files uploaded and stored via Storage can be accessed with the same Storage class. Try
<img src="{{ Storage::disk('public')->url('/uploads/' . $post->image) }}" alt=""
class="img-thumbnail">
asset() is used for accessing files in /public

Laravel Spatie unable to restrict UserController

Currently I have users.index blade which I would like to restrict. However, I failed to restrict it.
I have tried to create another test blade and a TestController and I have set permission to it and it works fine.
However with UserController, there is just no way to restrict Users from accessing it:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use DB;
class TestController extends Controller
{
/**
* Restricting pages
*/
public function __construct()
{
$this -> middleware('permission:test-list', ['only' => ['index']]);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('test.index');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($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)
{
//
}
}
views/test/index.blade.php
#extends('layouts.app')
#section('content')
<p>Testing Page</p>
#endsection
These are the results if I don't permit a particular user role to access this page.
enter image description here
enter image description here
So the above is the correct behavior.
However when it comes to user.index , I applied the same technique in the constructor of the UserController but it doesn't work
app/Http/Controllers/UserController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Spatie\Permission\Models\Role;
use DB;
use Hash;
class UserController extends Controller
{
public function construct()
{
$this -> middleware('permission:user-list', ['only' => ['index']]);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$data = User::orderBy('id','DESC') -> paginate(5);
return view('users.index' , compact('data')) -> with('i' , ($request->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$roles = Role::pluck('name','name') -> all();
return view('users.create',compact('roles'));
}
/**
* 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|unique:users,email',
'password' => 'required|same:confirm-password',
'roles' => 'required'
]);
$input = $request -> all();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
$user -> assignRole($request -> input('roles'));
return redirect() -> route('users.index') -> with('success','User created successfully');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$user = User::find($id);
return view('users.show',compact('user'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$user = User::find($id);
$roles = Role::pluck('name','name') -> all();
$userRole = $user->roles -> pluck('name','name') -> all();
return view('users.edit',compact('user','roles','userRole'));
}
/**
* 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, [
'name' => 'required',
'email' => 'required|email|unique:users,email,'.$id,
'password' => 'same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
if( ! empty($input['password'])) {
$input['password'] = Hash::make($input['password']);
} else {
$input = array_except($input,array('password'));
}
$user = User::find($id);
$user -> update($input);
DB::table('model_has_roles') -> where('model_id',$id) -> delete();
$user -> assignRole($request -> input('roles'));
return redirect() -> route('users.index') -> with('success','User updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
User::find($id) -> delete();
return redirect() -> route('users.index') -> with('success','User deleted successfully');
}
}
Result [I am still able to view this Blade in front end despite not having the permission to view this page]
enter image description here
This is my role-has-permission tablerole-has-permission
This is my role table
role
This is my permission table
permissions
This is my model-has-roles table model-has-roles
This is my model-has-permissions table model-has-permissions
If you want to restrict specific routes or all you can do something like this:
Route::middleware(['auth', 'permission:user-list'])->group(function (){
Route::get('/create', 'WelcomeController#create')->name('welcome');
...
...
..
});
or you can replace
public function construct()
{
$this -> middleware('permission:user-list', ['only' => ['index']]);
}
to
public function construct()
{
$this -> middleware('permission:user-list')->except(['index']);
}

Laravel Roles without pivot table

I am student and i am new with Laravel and i have this UserController which used to assign multi Roles to User (using pivot table user_role) but i want to assign one role to each user (without pivot table) so i added role_id foreign in table user but i dont know what to change in UserController file.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use App\Role;
use DB;
use Hash;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$data = User::orderBy('id','DESC')->paginate(5);
return view('users.index',compact('data'))
->with('i', ($request->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$roles = Role::pluck('display_name','id');
return view('users.create',compact('roles'));
}
/**
* 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|unique:users,email',
'password' => 'required|same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
foreach ($request->input('roles') as $key => $value) {
$user->attachRole($value);
}
return redirect()->route('users.index')
->with('success','User created successfully');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$user = User::find($id);
return view('users.show',compact('user'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$user = User::find($id);
$roles = Role::pluck('display_name','id');
$userRole = $user->roles->pluck('id','id')->toArray();
return view('users.edit',compact('user','roles','userRole'));
}
/**
* 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, [
'name' => 'required',
'email' => 'required|email|unique:users,email,'.$id,
'password' => 'same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
if(!empty($input['password'])){
$input['password'] = Hash::make($input['password']);
}else{
$input = array_except($input,array('password'));
}
$user = User::find($id);
$user->update($input);
DB::table('role_user')->where('user_id',$id)->delete();
foreach ($request->input('roles') as $key => $value) {
$user->attachRole($value);
}
return redirect()->route('users.index')
->with('success','User updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
User::find($id)->delete();
return redirect()->route('users.index')
->with('success','User deleted successfully');
}
}
and you can find all the code here:
http://itsolutionstuff.com/post/laravel-52-user-acl-roles-and-permissions-with-middleware-using-entrust-from-scratch-tutorialexample.html
this mean so much to me if you help me and thanks.

Categories