LadyDeathKZN

LadyDeathKZN

Member Since 1 Year Ago

Experience Points
3,020
Total
Experience

1,980 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
2
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 1
3,020 XP
May
18
1 week ago
Activity icon

Replied to Login Redirect Not Working With Laravel 7

Thank you! Still trying to get used to all the changes in Laravel 7. You been a great help, thank you!

Activity icon

Replied to Login Redirect Not Working With Laravel 7

Hi, I just tried your approach and it still doing the same thing. I haven't altered anything in the login view, so not 100% sure why the if statements are not working, I also took note of this in the standard blade syntax.

Here is the entire controller

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Auth;
use DB;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected function redirectTo()
    {
        //User Role
        $role = Auth::user()->role;
        //Check Role
        if($role == 'employee'){
            DB::table('login_record')->insert([
                'user_email' => Auth::user()->email,
                'login_ip' => request()->getClientIp(),
                'created_at' => now(),
            ]);
            session()->flash('success', 'Welcome, '. Auth::user()->name .'! You are Logged In.');
            return redirect()->route('home');
        } elseif($role == 'admin') {
            DB::table('login_record')->insert([
                'user_email' => Auth::user()->email,
                'login_ip' => request()->getClientIp(),
                'created_at' => now(),
            ]);
            session()->flash('success', 'Welcome, '. Auth::user()->name .'! You are Logged into the Admin Portal.');
            return redirect()->route('adminDashboard');
        }
    }

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
}

Activity icon

Started a new Conversation Login Redirect Not Working With Laravel 7

Hi, I have set up a role in the user table. This code is working in Laravel 6. It does absolutely nothing, just logs them in and redirects to the welcome page.

protected function redirectTo()
    {
        //User Role
        $role = Auth::user()->role;
        //Check Role
        if($role == 'employee'){
            DB::table('login_record')->insert([
                'user_email' => Auth::user()->email,
                'login_ip' => request()->getClientIp(),
                'created_at' => now(),
            ]);
            session()->flash('success', 'Welcome, '. Auth::user()->name .'! You are Logged In.');
            return route('home');
        } elseif($role == 'admin') {
            DB::table('login_record')->insert([
                'user_email' => Auth::user()->email,
                'login_ip' => request()->getClientIp(),
                'created_at' => now(),
            ]);
            session()->flash('success', 'Welcome, '. Auth::user()->name .'! You are Logged into the Admin Portal.');
            return route('adminDashboard');
        }
    }
May
14
2 weeks ago
Activity icon

Started a new Conversation $data Array Not Pulling To View Laravel 7

I am having issues getting the $data array to send to the markdown template. In Controller

use App\Mail\UserCreated;
use Illuminate\Support\Facades\Mail;

// Mail New User
        $data = array([
            'name' => $request->name,
            'email' => $request->email,
            'password' => $request->password,
        ]);
        Mail::to($request->email)->send(new UserCreated($data));

UserCreated.php

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class UserCreated extends Mailable
{
    use Queueable, SerializesModels;
    public $data;
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->from('[email protected]')->subject('New User Added')->markdown('emails.userCreated');
    }
}

MarkDown

@component('mail::message')
Hi, {{$data['name']}}!

You have been added to the Self Assessment System.

useremail: {{$data['email']}}
password: {{$data['password']}}

@component('mail::button', ['url' => ''])
Get Started
@endcomponent

Thanks,<br>
{{ config('app.name') }}
@endcomponent

It's like the build() does not want to take the $data

Feb
17
3 months ago
Activity icon

Started a new Conversation Cant Access Apart Folder In Public

Hi,

I followed the instruction to remove public from the url, by changing the server.php and so on. I have a codeigniter application in /public/accounts and can no longer access it. How do I go about this?

Jan
10
4 months ago
Activity icon

Started a new Conversation Remove The Last Entry Created By Push

Hi, I was wanting to know how could I grab the "user" variable from the push function when it is created and use this to delete the node it is in using the remove() function for firebase. I am still a big noobie with Javascript and Firebase.

// Reference to your entire Firebase database
var db_ref = firebase.database().ref();
var object = db_ref.child("locations");

function alert (location) {
    navigator.geolocation.getCurrentPosition(function(location) {
        console.log(location.coords.latitude);
        console.log(location.coords.longitude);
        console.log(location.coords.accuracy);
        object.push({
            "user": 'name_' + Math.floor(Math.random() * 90 + 10) +'',
            "lat": location.coords.latitude,
            "lng": location.coords.longitude,
            "name": "NEW ALERT",
            "message": "new alert"
        });
        console.log("Alert Sent");
    });
}

function disarm() {
    object.child().remove();
    console.log("Alert Disarmed")
}

Any advice would be appreciated. I basically want to be able to remove the entry the push function has created for this specific instance.

Jan
07
4 months ago
Activity icon

Started a new Conversation Googlemap Marker Update With Firebase Data

Hi, I have built a simple google map page that pulls the markers directly from my firebase database. I would like to have the map update automatically (well in other terms I want to turn this project into a RealTime Application), for example if I delete a location in the DB then the page should update without having to manually refreshing. I have tried Angular and it confuses me too much. Any suggestions would be greatly appreciated.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <style>
    html,
    body,
    #map_canvas {
    height: 100%;
    width: 100%;
    margin: 0px;
    padding: 0px
    }
    </style>

    <link href="https://bootswatch.com/4/lux/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js" integrity="sha384-6khuMg9gaYr5AxOqhkVIODVIvm9ynTT5J4V1cfthmT+emCG6yVmEZsRHdxlotUnm" crossorigin="anonymous"></script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBf9HbUeJUgk5Qg7Cmkjlk0hGi5UViExtE"></script>
    <script src="https://www.gstatic.com/firebasejs/4.12.1/firebase.js"></script>
    <script src="https://cdn.firebase.com/libs/geofire/4.1.2/geofire.min.js"></script>
    <script>
        function initialize() {
        var infowindow = new google.maps.InfoWindow();
        var map = new google.maps.Map(
            document.getElementById("map_canvas"), {
            center: new google.maps.LatLng(37.4419, -122.1419),
            zoom: 13,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        //Initialize Firebase
        var config = {
            //have removed for the post, but it does connect and work
        };
        firebase.initializeApp(config);
        //Create a node at firebase location to add locations as child keys
        var locationsRef = firebase.database().ref("locations");
        var bounds = new google.maps.LatLngBounds();
            locationsRef.on('child_added', function(snapshot) {
                var data = snapshot.val();
                console.log(data);
                var marker = new google.maps.Marker({
                position: {
                    lat: data.lat,
                    lng: data.lng
                },
                map: map,
                label: {
                    color: 'white',
                    fontWeight: 'bold',
                    text: data.user
                }
                });
                bounds.extend(marker.getPosition());
                marker.addListener('click', (function(data) {
                return function(e) {
                    infowindow.setContent(data.name + "<br>" + this.getPosition().toUrlValue(6) + "<br>" + data.message + "<br>" + "User:" + data.user);
                    infowindow.open(map, this);
                }
                }(data)));
                map.fitBounds(bounds);
            });
        }

        google.maps.event.addDomListener(window, "load", initialize);
    </script>

    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <a class="navbar-brand" href="#">Navbar</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
        </button>
    
        <div class="collapse navbar-collapse" id="navbarColor01">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item active">
            <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
            </li>
            <li class="nav-item">
            <a class="nav-link" href="#">Features</a>
            </li>
            <li class="nav-item">
            <a class="nav-link" href="#">Pricing</a>
            </li>
            <li class="nav-item">
            <a class="nav-link" href="#">About</a>
            </li>
        </ul>
        <form class="form-inline my-2 my-lg-0">
            <input class="form-control mr-sm-2" type="text" placeholder="Search">
            <button class="btn btn-secondary my-2 my-sm-0" type="submit">Search</button>
        </form>
        </div>
    </nav>

    <div class="container-fluid">

        <div class="row">
            <div class="col-md-4">
                <div class="card text-white bg-primary mb-3" style="max-width: 20rem;">
                <div class="card-header">Header</div>
                <div class="card-body">
                    <h4 class="card-title">Primary card title</h4>
                    <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
                </div>
            </div>
            </div>
            <div class="col-md-8">
                <table class="table table-hover">
                    <thead>
                        <tr>
                        <th scope="col">Type</th>
                        <th scope="col">Column heading</th>
                        <th scope="col">Column heading</th>
                        <th scope="col">Column heading</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr class="table-active">
                        <th scope="row">Active</th>
                        <td>Column content</td>
                        <td>Column content</td>
                        <td>Column content</td>
                        </tr>
                        <tr>
                        <th scope="row">Default</th>
                        <td>Column content</td>
                        <td>Column content</td>
                        <td>Column content</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

    </div>
    <div id="map_canvas"></div>

</body>
</html>

JSON example

{
    "locations" : [
        {"lat":25.7616798,"lng":-80.19179020000001,"message":"Miami, FL, USA","name":"Miami, FL","user":"name_1"},
        {"lat":33.7489954,"lng":-84.3879824,"message":"Atlanta, GA, USA","name":"Atlanta, GA","user":"name_2"},
        {"lat":35.2270869,"lng":-80.84312669999997,"message":"Charlotte, NC, USA","name":"Charlotte, NC","user":"name_3"},
        {"lat":39.2903848,"lng":-76.61218930000001,"message":"Baltimore, MD, USA","name":"Baltimore, MD","user":"name_4"},
        {"lat":39.9525839,"lng":-75.16522150000003,"message":"Philadelphia, PA, USA","name":"Philadelphia, PA","user":"name_5"},
        {"lat":40.7127753,"lng":-74.0059728,"message":"New York, NY, USA","name":"New York, NY","user":"name_6"},
        {"lat":43.15657789999999,"lng":-77.60884650000003,"message":"Rochester, NY, USA","name":"Rochester, NY","user":"name_7"},
        {"lat":41.7658043,"lng":-72.67337229999998,"message":"Hartford, CT, USA","name":"Hartford, CT","user":"name_8"},
        {"lat":41.8239891,"lng":-71.41283429999999,"message":"Providence, RI, USA","name":"Providence, RI","user":"name_9"},
        {"lat":42.3600825,"lng":-71.05888010000001,"message":"Boston, MA, USA","name":"Boston, MA","user":"name_10"}
    ]
}
Dec
10
5 months ago
Activity icon

Started a new Conversation Increment String

Hi I have used several examples of incrementing strings. The first one works obviously "CYB-0001", but the incremementing just gives an entire array of the whole row.

public function confirmOrder() {
        $user = Auth::user()->name;
        #OrderNumber Generator
        if ($orderNumberFind = OrderProduct::where('order_id', '!=', null)->first()) {
            $orderNumberFind = $orderNumberFind++;
        } else {
            $orderNumberFind = 'CYB-00001';
        }

        $cartItems = OrderProduct::where('session', '=', Session::get('session'))->get();
        foreach($cartItems as $item){
            $item = DB::table('order_products')->update([
                'status' => 'pending',
                'updated_at' => now(),
                'order_id' => $orderNumberFind,
            ]);
        }
        $shopCartClears = ShopCart::where('session', Session::get('session'))->get();
        foreach($shopCartClears as $clear) {
            $clear = DB::table('shop_carts')->where('session', Session::get('session'))->delete();
        }

        return redirect()->route('orderSingle', $orderNumberFind, $user);
    }
Dec
04
5 months ago
Activity icon

Awarded Best Reply on Send Data To Partial View

Github post helped me :). https://stackoverflow.com/questions/45814650/laravel-redirect-back-with-variable-not-working

5

The problem was that I thought that writing return back()->with('bladeVar', $controllerVar) was the same as return view('test')->with('bladeVar', $controllerVar);,but it wasn't .

You cannot echo a variable using blade normal syntax: {{ $bladeVar }}, Instead, you have to access the session to get the value: {{ session('bladeVar') }}.

After I changed the way I displayed the data all worked as expected.
Activity icon

Replied to Send Data To Partial View

Github post helped me :). https://stackoverflow.com/questions/45814650/laravel-redirect-back-with-variable-not-working

5

The problem was that I thought that writing return back()->with('bladeVar', $controllerVar) was the same as return view('test')->with('bladeVar', $controllerVar);,but it wasn't .

You cannot echo a variable using blade normal syntax: {{ $bladeVar }}, Instead, you have to access the session to get the value: {{ session('bladeVar') }}.

After I changed the way I displayed the data all worked as expected.
Dec
03
5 months ago
Activity icon

Replied to Send Data To Partial View

@include('partials.frontend.domains', ['extension' => $extension])

Controller:

public function domainSearch(Request $request){
        $domain_name = $request->domain;
        $domain_name_no_space = str_replace(" ","",$domain_name);
        $contents = file_get_contents("http://co.za/cgi-bin/whois.sh?Domain=$domain_name_no_space");
        $extension = substr($domain_name, stripos($domain_name, '.'));
        if (strpos($contents, 'No Matches') !== false) {
            return redirect()->route('domains', compact('extension'))->with('not registered', $domain_name_no_space . ' is not taken');
        }
        else{
            return redirect()->route('domains', compact('extension'))->with('registered', $domain_name_no_space .' is taken');
        }
    }
Activity icon

Replied to Send Data To Partial View

Hi,

I have tried that I keep getting this error:

syntax error, unexpected end of file, expecting variable (T_VARIABLE) or ${ (T_DOLLAR_OPEN_CURLY_BRACES) or {$ (T_CURLY_OPEN)
Activity icon

Started a new Conversation Send Data To Partial View

Hi, I have a partial view that changes according to the controller. I want to send the $extension to this partial view, how can I go about doing this?

public function domainSearch(Request $request){
        $domain_name = $request->domain;
        $domain_name_no_space = str_replace(" ","",$domain_name);
        $contents = file_get_contents("http://co.za/cgi-bin/whois.sh?Domain=$domain_name_no_space");
        $extension = substr($domain_name, stripos($domain_name, '.'));
        if (strpos($contents, 'No Matches') !== false) {
            return redirect()->route('domains')->with('not registered', $domain_name_no_space . ' is not taken');
        }
        else{
            return redirect()->route('domains')->with('registered', $domain_name_no_space .' is taken');
        }
    }

View blade.php

...
@include('partials.frontend.pagehero')
<!-- text page-->
@include('partials.frontend.domains')
<section class="padding-small">
...

Partial View

@if (session()->has('registered'))
    <div class="container-fluid p-0">
        <div class="share-product red-bg d-flex align-items-center justify-content-center flex-column flex-md-row p-5">
            <div class="col-md-6 text-center">
                <h2>{!! session()->get('registered') !!}</h2>
                <p class="text-white">See what else is available!</p>
            </div>
            <div class="col-md-6">
                <form action="{{route('domainSearch')}}" method="post">
                    @csrf
                    <div class="input-group mb-3" id="input-domain">
                    <input type="text" class="form-control is-invalid" id="domain" name="domain" placeholder="{!! session()->get('registered') !!}">
                        <div class="input-group-append">
                            <button class="btn btn-dark btn-sm" type="submit">Something Else?</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
@elseif (session()->has('not registered'))
    <div class="container-fluid p-0">
        <div class="share-product green-bg d-flex align-items-center justify-content-center flex-column flex-md-row p-5">
            <div class="col-md-6 text-center">
                <h2>{!! session()->get('not registered') !!}</h2>
                <a href="#" class="btn btn-dark btn-sm">Purchase</a>
            </div>
            <div class="col-md-6">
                <form action="{{route('domainSearch')}}" method="post">
                    @csrf
                    <div class="input-group mb-3" id="input-domain">
                    <input type="text" class="form-control is-valid" id="domain" name="domain" placeholder="{!! session()->get('not registered') !!}">
                        <div class="input-group-append">
                            <button class="btn btn-dark btn-sm" type="submit">Something Else?</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
@else
<div class="container-fluid p-0">
    <div class="share-product blue-bg d-flex align-items-center justify-content-center flex-column flex-md-row p-5">
        <div class="col-md-6 text-center">
            <h2>Got a domain in mind?</h2>
            <p class="text-white">Let's check if it is available!</p>
        </div>
        <div class="col-md-6">
            <form action="{{route('domainSearch')}}" method="post">
                @csrf
                <div class="input-group mb-3" id="input-domain">
                <input type="text" class="form-control" id="domain" name="domain" placeholder="Search Domains">
                    <div class="input-group-append">
                        <button class="btn btn-dark btn-sm" type="submit">Check It Out</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
@endif

I have tried adding the ['extension'=>$extension] to the @include, I keep getting an error. I am not sure how to implement this.

Activity icon

Replied to Check Available / Unavailable With Php/javascript

Thank you I didn't even think about this!

Activity icon

Started a new Conversation Check Available / Unavailable With Php/javascript

Hi,

I have been battling to get a proper whois server for .co.za or any South African Domains. My Registrar has provided the code below. I would like to use this but have the site not redirect to their website the states are available and unavailable. Is there a way I can use php or javascript to check this state and return a message on my website rather than having the client redirected?

 <form action="https://instantbilling.co.za/cart.php?a=add&domain=register" method="post" class="domain-form">
            <input type="search" placeholder="Type a domain name..." name="query" size="20">
            <div class="search-sub">

              <button input type="submit" value="Go">check</button>
            </div>
          </form>

And if so how will I go about doing this? Unless someone has a working whois server for .co.za ?

Nov
26
6 months ago
Activity icon

Replied to Cannot Delete Product Record

Thank you I found the issue! :).

Activity icon

Started a new Conversation Cannot Delete Product Record

Hi,

I am having issues with deleting my record after all the other things have run. All the processes work wonderfully right up to $product->delete();

Then I get this error:

SQLSTATE[23000]: Integrity constraint violation: 19 FOREIGN KEY constraint failed (SQL: delete from "products" where "id" = 3)

My controller

public function destroy($id)
    {
        $product = Product::find($id);
        if($product->main_image != null){
            unlink(public_path($product->main_image));
        }
        //Images delete
        foreach(DB::table('image_products')->where('product_id', '=', $product->id)->get() as $imagepath){
            unlink(public_path($imagepath->image_path));
            DB::table('image_products')->where('product_id', '=', $product->id)->delete();
        }
        //Tags, Categories & Attributes
        $product->tags()->detach();
        $product->categories()->detach();
        $product->attributes()->detach();
        $product->delete();

        return redirect()->route('products.index')->with('error', 'Product deleted successfully');
    }

Migration

Schema::create('products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('main_image');
            $table->string('title');
            $table->string('alt')->nullable();
            $table->string('slug');
            $table->string('excerpt')->nullable();
            $table->longText('description')->nullable();
            $table->longText('specifications')->nullable();
            $table->longText('features')->nullable();
            $table->string('price')->nullable();
            $table->string('onsale_price')->nullable();
            $table->string('stock')->nullable();
            $table->string('type')->default('shop');
            $table->string('featured')->default('no');
            $table->string('status')->default('enabled');
            $table->integer('user_id')->unsigned()->nullable();
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });
Activity icon

Awarded Best Reply on Detach And Unlink Images

Hey I found a work around, I sadly don't have much time on this project:

public function update(Request $request, $id)
    {
        $product = Product::find($id);
        if($request->hasfile('main_image')){
            /* unlink(public_path($product->main_image)); */
            $image = $request->file('main_image');
            $filename = 'cyberware-'.$image->getClientOriginalName();
            $location = public_path('storage/frontend/products/'.$filename);
            Image::make($image)->save($location);
            $product->main_image = Storage::url('frontend/products/'.$filename);
        }
        $product->title = $request->title;
        $product->alt = $request->alt;
        $product->slug = $request->slug;
        $product->excerpt = $request->excerpt;
        $product->description = $request->description;
        $product->specifications = $request->specifications;
        $product->features = $request->features;
        $product->price = $request->price;
        $product->onsale_price = $request->onsale_price;
        $product->stock = $request->stock;
        $product->type = $request->type;
        $product->featured = $request->featured;
        $product->status = $request->status;
        $product->save();

        //Images
        if($request->hasfile('images') && $product->save()) {

            foreach(DB::table('image_products')->where('product_id', '=', $product->id)->get() as $imagepath){
                unlink(public_path($imagepath->image_path));
                DB::table('image_products')->where('product_id', '=', $product->id)->delete();
            }
            foreach($request->images as $image){
                $filename = $image->getClientOriginalName();
                $location = public_path('storage/frontend/products/extras/'.$filename);
                Image::make($image)->save($location);
                if(DB::table('image_products')->where('product_id', '==', null)){
                    DB::table('image_products')->insert([
                        'image_path' => Storage::url('frontend/products/extras/'.$filename),
                        'product_id' => $product->id,
                    ]);
                } else {
                    DB::table('image_products')->where('product_id', '==', $product->id)->update([
                        'image_path' => Storage::url('frontend/products/extras/'.$filename),
                        'product_id' => $product->id,
                    ]);
                }
            }
        }

        //Tags, Categories & Attributes
        if($product->save()){
            $product->tags()->sync($request->tags);
            $product->categories()->sync($request->category);
            $product->attributes()->sync($request->attribute);
        }

        return redirect()->route('products.index',)->with('warning', 'Product updated successfully');
    }
Nov
25
6 months ago
Activity icon

Replied to Detach And Unlink Images

Hey I found a work around, I sadly don't have much time on this project:

public function update(Request $request, $id)
    {
        $product = Product::find($id);
        if($request->hasfile('main_image')){
            /* unlink(public_path($product->main_image)); */
            $image = $request->file('main_image');
            $filename = 'cyberware-'.$image->getClientOriginalName();
            $location = public_path('storage/frontend/products/'.$filename);
            Image::make($image)->save($location);
            $product->main_image = Storage::url('frontend/products/'.$filename);
        }
        $product->title = $request->title;
        $product->alt = $request->alt;
        $product->slug = $request->slug;
        $product->excerpt = $request->excerpt;
        $product->description = $request->description;
        $product->specifications = $request->specifications;
        $product->features = $request->features;
        $product->price = $request->price;
        $product->onsale_price = $request->onsale_price;
        $product->stock = $request->stock;
        $product->type = $request->type;
        $product->featured = $request->featured;
        $product->status = $request->status;
        $product->save();

        //Images
        if($request->hasfile('images') && $product->save()) {

            foreach(DB::table('image_products')->where('product_id', '=', $product->id)->get() as $imagepath){
                unlink(public_path($imagepath->image_path));
                DB::table('image_products')->where('product_id', '=', $product->id)->delete();
            }
            foreach($request->images as $image){
                $filename = $image->getClientOriginalName();
                $location = public_path('storage/frontend/products/extras/'.$filename);
                Image::make($image)->save($location);
                if(DB::table('image_products')->where('product_id', '==', null)){
                    DB::table('image_products')->insert([
                        'image_path' => Storage::url('frontend/products/extras/'.$filename),
                        'product_id' => $product->id,
                    ]);
                } else {
                    DB::table('image_products')->where('product_id', '==', $product->id)->update([
                        'image_path' => Storage::url('frontend/products/extras/'.$filename),
                        'product_id' => $product->id,
                    ]);
                }
            }
        }

        //Tags, Categories & Attributes
        if($product->save()){
            $product->tags()->sync($request->tags);
            $product->categories()->sync($request->category);
            $product->attributes()->sync($request->attribute);
        }

        return redirect()->route('products.index',)->with('warning', 'Product updated successfully');
    }
Activity icon

Replied to Detach And Unlink Images

Hi, I fixed my code. Not sure what the heck went wrong. Your delete method for the file does not work, I have also tried the unlink with it and it is returning no path.

The update and store works now, thought the update does not delete the other files.

Activity icon

Replied to Detach And Unlink Images

I have cleared the view, route, cache and config via the CLI. But this won't even find the records and it is there:

App\ImageProduct::where('product_id', '=', $product->id)->count()

I have tried DB::table, nothing, the foreach as well. Any idea what could be doing this? The table is indeed the same name image_products.

Activity icon

Replied to Detach And Unlink Images

Hi,

Thank you for the reply! I have tested the code in several ways but get errors. Not sure what I have done but my entire products controller and blades are acting oddly. Will redo all and try again, so may bug you sometime again.