skip to Main Content

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 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 detail (i looked for the threads here and there and I don’t know if they can help or if they meet my need)

, my routes in web.php:

type here
use AppHttpControllersAdminController;
use AppHttpControllersHomeController;
use IlluminateSupportFacadesRoute;
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 many of its features

2

Answers


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

    <?php
    
    namespace AppHttpControllers;
    
    use AppCategory;
    use AppPost;
    use AppTag;
    use IlluminateHttpRequest;
    use IlluminateSupportFacadesAuth;
    use IlluminateSupportStr;
    
    class PostController extends Controller
    {
        public function __construct()
        {
            $this->middleware('admin');
        }
    
        /**
         * Display a listing of the resource.
         *
         * @return IlluminateHttpResponse
         */
        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 IlluminateHttpResponse
         */
        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  IlluminateHttpRequest  $request
         * @return IlluminateHttpResponse
         */
        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 IlluminateHttpResponse
         */
        public function show($id)
        {
            //
        }
    
        /**
         * Show the form for editing the specified resource.
         *
         * @param  int  $id
         * @return IlluminateHttpResponse
         */
        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  IlluminateHttpRequest  $request
         * @param  int  $id
         * @return IlluminateHttpResponse
         */
        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 IlluminateHttpResponse
         */
        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');
            }
    
    
        }
    
    
    
    }
    
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search