OsamaTheCoder
OsamaTheCoder

Reputation: 21

Laravel Sweet Alert how to store an alert in session and display it on success

I am using Sweet Alert from RealRashid and I need when the user create a category it redirects him to the index page and alert success message

store function

public function store(Request $request)
{
    $imageUploaded = false;

    $validator = Validator::make($request->all(), [
        'title' => 'required|string|max:100',
        'title_ar' => 'required|string|max:100',
        'img' => 'required|image|mimes:jpeg,png,jpg',
    ]);

    if ($validator->fails()) {
        $errors = $validator->errors();
        return redirect(route('categories.create'))->withErrorMessage($errors);
    }

    if ($request->has('img')) {
        $img = $request->file('img');
        $ext = $img->getClientOriginalExtension();
        $img_name = 'category-' . uniqid() . ".$ext";
        $stored = $img->move(public_path('uploads/categories/'), $img_name);
        if ($stored) {
            $imageUploaded = true;
        } else {
            return redirect(route('categories.create'))->withUploadErrorMessage('Error Uploading Image');
        }
    }

    $title = $request->title;
    $title_ar = $request->title_ar;

    if ($imageUploaded) {
        Category::create([
            'title' => $title,
            'title_ar' => $title_ar,
            'img' => $img_name
        ]);
    }

    return redirect()->route('categories')
        ->withSuccessMessage('Category Created Successfully');
}

and in the index page I am checking for success message and alerting it like that

public function index()
{
    if (session('success_message')) {
        Alert::success('Success!', session('success_message'));
    }
    if (session('error_message')) {
        $errors_arr = [];
        foreach (session('error_message')->messages() as $error) {
            array_push($errors_arr, $error[0]);
        }
        $errors_html = collect($errors_arr)->implode('<br>');
        Alert::html('Error', $errors_html, 'error');
    }

    $categories = Category::latest()->get();

    return view('dashboard/categories/categories', compact('categories'));
}

And I imported the sweet alert library in the master layout

@include('sweetalert::alert')

But it's redirecting me to the index page without alerting anything

What can be the problem here?

Upvotes: 0

Views: 801

Answers (1)

Amir Reza Tavakolian
Amir Reza Tavakolian

Reputation: 51

when your work is done use with() or other methods to set a session

return redirect('users')->with('success', '$url');

now check if session is set, then you can show the alert

<script>
    @if(session('succes'))
        swal("{{ session('succes') }}");
    @endif
</script>

Upvotes: 0

Related Questions