2

I am trying to crud the image but it say undefined variable reimage code: CategoryController

/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response
 */
public function create()
{
    return view('admin.category.add');
}

/**
 * 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|min:5|max:20',
        'detail' => 'required',
        'cat_image' => 'required',
    ]);

    if($request->hasFile('cat_image')){
        $image = $request->file('cat_image');
        $reimage = time().'.'.$image->getClientOriginalExtension();
        $dest = public_path('/imgs');
        $image->move($dest,$reimage);
    }

    $category = new Category;
    $category->title= $request->title;
    $category->title= $request->title;
    $category->image= $reimage;
    $category->save();

return redirect('admin/category/create')->with('Data has been added succesfully');

}

web.php

  <?php
    
   

     use Illuminate\Support\Facades\Route;
        use App\Http\Controllers\HomeController;
        use App\Http\Controllers\AdminController;
        use App\Http\Controllers\CategoryController;
        
        /*
        |--------------------------------------------------------------------------
        | 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('/', function () {
            return view('welcome');
        }); */
        
        Route::get('/',[HomeController::class,'home']);
        
        Route::get('/login',[AdminController::class,'login']);
        Route::post('/login',[AdminController::class,'submit_login'])->name('submit_login');
        Route::get('/admin',[AdminController::class,'dashboard']);
        Route::resource('/admin/category',CategoryController::class)

add.blade.php **

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
        <meta name="description" content="" />
        <meta name="author" content="" />
        <title>Static Navigation - SB Admin</title>
        <link href="{{ URL::to('/css/styles.css') }}" rel="stylesheet" />
        <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js" crossorigin="anonymous"></script>
    </head>
    <body>
        <nav class="sb-topnav navbar navbar-expand navbar-dark bg-dark">
            <!-- Navbar Brand-->
            <a class="navbar-brand ps-3" href="index.html">Start Bootstrap</a>
            <!-- Sidebar Toggle-->
            <button class="btn btn-link btn-sm order-1 order-lg-0 me-4 me-lg-0" id="sidebarToggle" href="#!"><i class="fas fa-bars"></i></button>
            <!-- Navbar Search-->
            <form class="d-none d-md-inline-block form-inline ms-auto me-0 me-md-3 my-2 my-md-0">
                <div class="input-group">
                    <input class="form-control" type="text" placeholder="Search for..." aria-label="Search for..." aria-describedby="btnNavbarSearch" />
                    <button class="btn btn-primary" id="btnNavbarSearch" type="button"><i class="fas fa-search"></i></button>
                </div>
            </form>
            <!-- Navbar-->
            <ul class="navbar-nav ms-auto ms-md-0 me-3 me-lg-4">
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" id="navbarDropdown" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"><i class="fas fa-user fa-fw"></i></a>
                    <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
                        <li><a class="dropdown-item" href="#!">Settings</a></li>
                        <li><a class="dropdown-item" href="#!">Activity Log</a></li>
                        <li><hr class="dropdown-divider" /></li>
                        <li><a class="dropdown-item" href="#!">Logout</a></li>
                    </ul>
                </li>
            </ul>
        </nav>
        <div id="layoutSidenav">
            <div id="layoutSidenav_nav">
                <nav class="sb-sidenav accordion sb-sidenav-dark" id="sidenavAccordion">
                    <div class="sb-sidenav-menu">
                        <div class="nav">
                            <div class="sb-sidenav-menu-heading">Core</div>
                            <a class="nav-link" href="index.html">
                                <div class="sb-nav-link-icon"><i class="fas fa-tachometer-alt"></i></div>
                                Dashboard
                            </a>
                            <div class="sb-sidenav-menu-heading">Interface</div>
                            <a class="nav-link collapsed" href="#" data-bs-toggle="collapse" data-bs-target="#collapseLayouts" aria-expanded="false" aria-controls="collapseLayouts">
                                <div class="sb-nav-link-icon"><i class="fas fa-columns"></i></div>
                                Layouts
                                <div class="sb-sidenav-collapse-arrow"><i class="fas fa-angle-down"></i></div>
                            </a>
                            <div class="collapse" id="collapseLayouts" aria-labelledby="headingOne" data-bs-parent="#sidenavAccordion">
                                <nav class="sb-sidenav-menu-nested nav">
                                    <a class="nav-link" href="layout-static.html">Static Navigation</a>
                                    <a class="nav-link" href="layout-sidenav-light.html">Light Sidenav</a>
                                </nav>
                            </div>
                            <a class="nav-link collapsed" href="#" data-bs-toggle="collapse" data-bs-target="#collapsePages" aria-expanded="false" aria-controls="collapsePages">
                                <div class="sb-nav-link-icon"><i class="fas fa-book-open"></i></div>
                                Pages
                                <div class="sb-sidenav-collapse-arrow"><i class="fas fa-angle-down"></i></div>
                            </a>
                            <div class="collapse" id="collapsePages" aria-labelledby="headingTwo" data-bs-parent="#sidenavAccordion">
                                <nav class="sb-sidenav-menu-nested nav accordion" id="sidenavAccordionPages">
                                    <a class="nav-link collapsed" href="#" data-bs-toggle="collapse" data-bs-target="#pagesCollapseAuth" aria-expanded="false" aria-controls="pagesCollapseAuth">
                                        Authentication
                                        <div class="sb-sidenav-collapse-arrow"><i class="fas fa-angle-down"></i></div>
                                    </a>
                                    <div class="collapse" id="pagesCollapseAuth" aria-labelledby="headingOne" data-bs-parent="#sidenavAccordionPages">
                                        <nav class="sb-sidenav-menu-nested nav">
                                            <a class="nav-link" href="login.html">Login</a>
                                            <a class="nav-link" href="register.html">Register</a>
                                            <a class="nav-link" href="password.html">Forgot Password</a>
                                        </nav>
                                    </div>
                                    <a class="nav-link collapsed" href="#" data-bs-toggle="collapse" data-bs-target="#pagesCollapseError" aria-expanded="false" aria-controls="pagesCollapseError">
                                        Error
                                        <div class="sb-sidenav-collapse-arrow"><i class="fas fa-angle-down"></i></div>
                                    </a>
                                    <div class="collapse" id="pagesCollapseError" aria-labelledby="headingOne" data-bs-parent="#sidenavAccordionPages">
                                        <nav class="sb-sidenav-menu-nested nav">
                                            <a class="nav-link" href="401.html">401 Page</a>
                                            <a class="nav-link" href="404.html">404 Page</a>
                                            <a class="nav-link" href="500.html">500 Page</a>
                                        </nav>
                                    </div>
                                </nav>
                            </div>
                            <div class="sb-sidenav-menu-heading">Addons</div>
                            <a class="nav-link" href="charts.html">
                                <div class="sb-nav-link-icon"><i class="fas fa-chart-area"></i></div>
                                Charts
                            </a>
                            <a class="nav-link" href="tables.html">
                                <div class="sb-nav-link-icon"><i class="fas fa-table"></i></div>
                                Tables
                            </a>
                        </div>
                    </div>
                    <div class="sb-sidenav-footer">
                        <div class="small">Logged in as:</div>
                        Start Bootstrap
                    </div>
                </nav>
            </div>
            <div id="layoutSidenav_content">
                <main>
                    <div class="container-fluid px-4">
                        <h1 class="mt-4">Create Category</h1>
                        <ol class="breadcrumb mb-4">
                            <li class="breadcrumb-item"><a href="index.html">Dashboard</a></li>
                            <li class="breadcrumb-item active">Create Category</li>
                        </ol>
                        <div class="card mb-4">
                            <div class="card-header">
                            <h1>Create</h1>
                            </div>
                            <div class="card-body">
                            @if($errors)
                                @foreach($errors->all() as $error)
                                    <p class="text-danger">{{ $error }}</p>
                                @endforeach
                            @endif
                            @if(Session::has('success'))
                                <p class="text-danger">{{ session('success') }}</p>
                            @endif
                            <form method="POST" action="{{ url('admin/category') }}" encrypt="multipart/form-data">
                            @csrf
                                <div class="form-group">
                                    <label for="exampleInputEmail1">Title</label>
                                    <input type="text" class="form-control" name="title" placeholder="Enter Title">
                                </div>
                                <div class="form-group">
                                    <label for="exampleInputPassword1">Detail</label>
                                    <input type="text" class="form-control" name="detail"  placeholder="Enter details about the category">
                                </div>
                                <div class="form-group">
                                    <label for="exampleInputPassword1">Image</label>
                                    <input type="file" class="form-control" name="cat_image" placeholder="Image">
                                    <small id="emailHelp" class="form-text text-muted">a jpg or png</small>
                                </div>
                                <button type="submit" class="btn btn-primary">Submit</button>
                                </form>
                            </div>
                        </div>
                        <div style="height: 100vh"></div>
                        <div class="card mb-4"><div class="card-body">When scrolling, the navigation stays at the top of the page. This is the end of the static navigation demo.</div></div>
                    </div>
                </main>
                <footer class="py-4 bg-light mt-auto">
                    <div class="container-fluid px-4">
                        <div class="d-flex align-items-center justify-content-between small">
                            <div class="text-muted">Copyright &copy; Your Website 2021</div>
                            <div>
                                <a href="#">Privacy Policy</a>
                                &middot;
                                <a href="#">Terms &amp; Conditions</a>
                            </div>
                        </div>
                    </div>
                </footer>
            </div>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
        <script src="{{ URL::to('/js/scripts.js') }}"></script>
    </body>
</html>

and I am trying to make new name for the photo as the name is time+the orginal name ml> and I am trying to make new name for the photo as the name is time+the orginal name ml> and I am trying to make new name for the photo as the name is time+the orginal name ml> and I am trying to make new name for the photo as the name is time+the orginal name ml> and I am trying to make new name for the photo as the name is time+the orginal name

**

Coder Moataz
  • 35
  • 1
  • 8
  • Does this answer your question? ["Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP](https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-and-notice-undefined) – Nico Haase Jun 22 '21 at 11:30
  • If that does not help, please add your attempts to resolve the problem to the question by editing it – Nico Haase Jun 22 '21 at 11:30
  • 2
    the proplem is the it doesn't define the variable reimage in CategoryController and it doesn't define it at line ** $category->image= $reimage;** I feel like this happen because $reimage is in if condition @NicoHaase – Coder Moataz Jun 22 '21 at 11:32
  • Yeah, then why do you want to use that variable if you already know that it is not initialized? – Nico Haase Jun 22 '21 at 11:33
  • I didn't understand you how I can use this variable even the if condition is important as to know if there is file or not and how can I use it without the if condition – Coder Moataz Jun 22 '21 at 11:35
  • 1
    Above the `if` statement you can write `$reimage = '';` or `$reimage = null;` to initialize the variable. Why not start with the basics? https://www.php.net/docs.php – Peter Krebs Jun 22 '21 at 11:45
  • the docs you are sending for php not for laravel ! – Coder Moataz Jun 22 '21 at 11:55
  • As Laravel is written in PHP, these docs also apply. So, please share your attempts to resolve the problem. Is there anything unclear about the given hints? – Nico Haase Jun 22 '21 at 12:18

1 Answers1

1

You are getting variable undefined because its only initialized inside IF condition and used below that code. In case IF condition is not true, variable never created and giving your error.

Simply initialized variable with empty string (or something else if its required DB field).

Here is your updated function

public function store(Request $request)
{
    $request->validate([
        'title' => 'required|min:5|max:20',
        'detail' => 'required',
        'cat_image' => 'required',
    ]);

    $reimage = '';
    if($request->hasFile('cat_image')){
        $image = $request->file('cat_image');
        $reimage = time().'.'.$image->getClientOriginalExtension();
        $dest = public_path('/imgs');
        $image->move($dest,$reimage);
    }

    $category = new Category;
    $category->title= $request->title;
    $category->title= $request->title;
    $category->image= $reimage;
    $category->save();

return redirect('admin/category/create')->with('Data has been added succesfully');
}

Also there is an error in html, form enctype is mis-spelled, and fix it and you will be receiving files on backend:

Yours

<form method="POST" action="{{ url('admin/category') }}" encrypt="multipart/form-data">

Correct one:

<form method="POST" action="{{ url('admin/category') }}" enctype="multipart/form-data">
Muneeb A.
  • 66
  • 5