Home > Net >  adding and deleting users from an admin dashboard in laravel
adding and deleting users from an admin dashboard in laravel

Time:01-07

hi there how is it going, i need help guys, i will appreciate it. i am trying to make a full website using laravel 9 and inside of it i am trying to make an admin account in which i can create, edit and delete other user accounts. i was able to delete the users but i still cannot create and edit them. i am a pure beginner and noob in laravel so i may need to be told how to do it step by step and in details (i looked for the threads here and there and i don't know they can help or they meet my need)

, my routes in web.php:

type here
use App\Http\Controllers\AdminController;
use App\Http\Controllers\HomeController;
use Illuminate\Support\Facades\Route;
Route::get('/adduser', [AdminController::class, 'adduser']);
Route::post('/users', [AdminController::class, 'store']);
Route::get('/edituser/{id}', [AdminController::class, 'edituser']);
Route::post('/edituser/{id}', [AdminController::class, 'update']);
Route::get('/deleteuser/{id}', [AdminController::class, 'deleteuser']);

my controller:

type here
public function user()
    {
        $data = user::all();

        return view('admin.users', compact('data'));
    }

    public function adduser()
    {
        return view('admin.adduser');
    }

    public function store(Request $request)
    {
        $userdata = $request;
        $userdata->name = $request->name;
        $userdata->password = $request->password;
        $userdata->usertype = $request->usertype;
        $userdata->save();

        return redirect()->back();
    }

 public function update($id) #this function is for editing the users
    {
        $data = user::find($id);
        $userdata = $request;
        $userdata->name = $request->name;
        $userdata->password = $request->password;
        $userdata->usertype = $request->usertype;
        $userdata->save();

        return redirect()->back();
    }

i didn't change anything in the default laravel users model, i don't know if i need to paste it here as well and if there are any other things to paste, please help me guys thank you i used the default auth of laravel and jetstream as well but didn't implement much of its features

CodePudding user response:

Your doing it wrong, you are using the $request instead the User model.

public function store(Request $request)
{
    /**
    * First of all you should validate the inputted value
    * to make sure that the inputted values are valid
    */

    $request->validate([
        'name' => 'required' // means that the name field in the form cannot be empty
        'password' => 'required' // same as the name field,
        'usertype' => 'required' // the keys should be same as the `name` attribute on the form
    ]);

    /**
    * After validating the user data you can now insert it to the database
    * you can use User::create(), User::query()->create() or create a new
    * instance of User model : $user = User;
    *
    * Take note that in the $user->usertype. The usertype is the column 
    * in your database. Just like in the $user->name and $user->password
    **/
    
    $user = new User; // we will use this since its almost identical to the one you make
    $user->name = $request->name;
    $user->password = Hash::make($request->password); // you need to hash the password so that the authenticate will not fail even if you put the correct password if you will use the `Auth` facade for authentication
    $user->usertype = $request->usertype


    /**
    * After you assign the the data to the proper "columns" you should save the 
    * User model so that it will save the data in the database. If you didn't
    * use the save() method it will not save the data in database.
    *
    * In case you use the User::create() or User::query()->create() you don't
    * have to call the save() method.
    **/

    $user->save();
    
    /**
    * After saving the data you can now redirect if you don't need to do anything
    *
    * Tip : back() is equivalent to redirect()->back()
    * In case you want to add a success message to return you can
    * back()->with(['success' => 'User added successfully !']) then you can
    * call it in the blade file using session('success')
    */
    return back(); // its the same as redirect()->back()

}

in update model its just like in the store model the difference is that you need the user id.

/**
* The parameter for update method is either update(User $id, Request $request)
* or update($id, Request $request)
* we will use the second one since its identical to the one you made
* You need to add Request $request as the parameter so that you can get the
* form data
*/

public function update($id, Request $request)
{
    $user = User::findOrFail($id); // just to make sure that the user exist if its not exists it will redirect to 404 not found page and will not throw an exception

    $request->validate([
        'name' => 'required',
        'password' => 'required',
        'usertype' => 'required'
    ]);

    /**
    * Since we already have the $user we can just skip the $user = new User;
    */

    $user->name = $request->name;
    $user->password = Hash::make($request->password);
    $user->usertype = $request->usertype;
    $user->save();

    return back()->with(['success' => 'User updated successfully.']);
}

It is the minimum requirement for CRUD but it is possible to create your own implementation. You can experiment to the methods I commented above.

If you want to learn more about Validation : Validation in Laravel

More about inserting and updating data in database using model : Eloquent in Laravel

Hope it helps, Happy Learning.

CodePudding user response:

This is my old code but also made when I was beginner :) Hope it will help you:

<?php

namespace App\Http\Controllers;

use App\Category;
use App\Post;
use App\Tag;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class PostController extends Controller
{
    public function __construct()
    {
        $this->middleware('admin');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $posts = Post::all();

        if($posts->count() == 0){
            return redirect()->route('posts.create')->with('toast_warning', 'You do not have any posts yet. Make some here!');
        }

        return view('admin.posts.index', ['posts' => $posts]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $categories = Category::all();
        $tags = Tag::all();

        if($categories->count() == 0){
            return redirect()->route('category.create')->with('toast_warning', 'You do not have any categories yet. Make some here!');
        } elseif ($tags->count() == 0){
            return redirect()->route('tags.create')->with('toast_warning', 'You do not have any tags yet. Make some here!');
        }

        return view('admin.posts.create', ['categories' => $categories, 'tags' => $tags]);
    }

    /**
     * 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|min:5|max:255',
           'content' => 'required|min:15',
            'featured' => 'required|image',
            'category_id' => 'required',
            'tags' => 'required'
        ]);

        $featured = $request->featured;

        $featured_new_name = time().$featured->getClientOriginalName();

        $featured->move('uploads/posts', $featured_new_name);

        $post = Post::create([
            'title' => $request->title,
            'content' => $request->content,
            'featured' => '/uploads/posts/' . $featured_new_name,
            'category_id' => $request->category_id,
            'slug' => Str::slug($request->title),
            'user_id' => Auth::id(),
        ]);

        $post->tags()->attach($request->tags);

        return redirect()->route('posts.index')->with('toast_success', 'Post has been created');

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $post = Post::findOrFail($id);
        $categories = Category::all();
        $tags = Tag::all();
        return view('admin.posts.edit', ['post' => $post, 'categories' => $categories, 'tags' => $tags]);
    }

    /**
     * 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, [
           'title' => 'required|min:5|max:255',
           'content' => 'required|min:5',
           'category_id' => 'required',
            'slug' => Str::slug($request->title),
        ]);

        $post = Post::findOrFail($id);

        if($request->hasFile('featured')){
            $featured = $request->featured;

            $featured_new_name = time() . $featured->getClientOriginalName();

            $featured->move('uploads/posts', $featured_new_name);

            $post->featured = '/uploads/posts/' . $featured_new_name;
        }

        $post->title = $request->title;
        $post->content = $request->content;
        $post->category_id = $request->category_id;
        $post->slug = Str::slug($request->title);

        $post->save();

        $post->tags()->sync($request->tags);

        return redirect()->route('posts.index')->with('toast_info', 'Post has been updated');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $post = Post::withTrashed()->where('id', $id)->first();
        $post->forceDelete();

        $trashed = Post::onlyTrashed()->get();

        if($trashed->count() == 0)
        {
            return redirect()->route('posts.index')->with('toast_error', 'Your post has been deleted');
        }
        else
        {
            return redirect()->back()->with('toast_error', 'Your post has been deleted');
        }

    }

    /**
     * This function is responsible for trashing posts
     *
     * */
    public function trash($id)
    {
        Post::findOrFail($id)->delete();

        return redirect()->route('posts.index')->with('toast_warning', 'Your post has been trashed');
    }

    /**
     * This function is displaying trashed posts
     *
     * */
    public function trashed(){
        $posts = Post::onlyTrashed()->get();

        return view('admin.posts.trashed', ['posts' => $posts]);
    }

    public function restore($id){
        $post = Post::withTrashed()->where('id', $id)->first();
        $post->restore();

        $trashed = Post::onlyTrashed()->get();

        if($trashed->count() == 0)
        {
            return redirect()->route('posts.index')->with('toast_success', 'Your post has been restored');
        }
        else
        {
            return redirect()->back()->with('toast_success', 'Your post has been restored');
        }


    }



}

  • Related