Our Black Friday sale is now live! All individual subscriptions are 50% OFF. This week only!

ErikRobles

ErikRobles

Member Since 2 Years Ago

Experience Points
2,220
Total
Experience

2,780 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
13
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
2,220 XP
Nov
24
1 day ago
Activity icon

Replied to On Live Server All Routes Leading To Home But Working Good In Local

DUH!!! I feel so stupid. I forgot to update the sql db to include the column role_as and give it admin . Sorry to bother you all. Thank you for helping.

Activity icon

Replied to On Live Server All Routes Leading To Home But Working Good In Local

OK. I now have ssh. Ran cache clear but still not directing to the correct routes. Only Home.

Activity icon

Replied to On Live Server All Routes Leading To Home But Working Good In Local

It could be. I am trying to set up ssh so I can dig deeper.

Activity icon

Replied to On Live Server All Routes Leading To Home But Working Good In Local

My routes were working before on the live server but I notices a vulnerability today so I protected my routes via middle ware and web.php. No my routes don't work on the live server but do in local with the changes.

Activity icon

Replied to On Live Server All Routes Leading To Home But Working Good In Local

Thank you @jlrdw. How do I do that if I am not using ssh?

Activity icon

Started a new Conversation On Live Server All Routes Leading To Home But Working Good In Local

Trouble routing in laravel 7 on live server. I have all my routes protected in the admin and in local, Every link works as expected. However, on my live server, every route leads to home. Even if I hover over the link, at the bottom I see the route referrenced correctly. For example https://mysite.com/admin. When I click it, it directs me home. What I am not clear on is what I need to do differently to get me routes back. Here is my Login Controller:

use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    // protected $redirectTo = RouteServiceProvider::HOME;

    protected $redirectTo = '/admin';

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

All my admin routes in web.php are wrapped inside the following:

Route::group(['middleware' => ['auth', 'isAdmin']], function () {
});

In my protected $routeMiddleware, I have:

 'isAdmin' =>  \App\Http\Middleware\AdminMiddleware::class,

My AdminMiddleware is as follows:

public function handle($request, Closure $next)
    {
        if (Auth::user()->role_as == 'admin') {
            return $next($request);
        } else {
            return redirect('/login')->with('error', 'You are not permitted to access the User dashboard.');
        }
    }

my routes are like: href="{{ route('myroute') }}" Any clues to watch out for when moving the site to the live server? Thank you.

Nov
23
2 days ago
Activity icon

Replied to Joining 3 Tables In Laravel

In answer to my own question, I had to change the query to the following:

$data['students'] = Oex_students::select('name','email','mobile_no','oex_exam_masters.title as exam_name','result','oex_exam_masters.status as status')
		->from('oex_students')
		->join('oex_results', function($join) {
			$join->on('oex_students.id', '=', 'oex_results.user_id');
			})
		->join('oex_exam_masters', function($join) {
			$join->on('oex_exam_masters.id', '=', 'oex_results.exam_id');
			})
		->get();
Activity icon

Started a new Conversation Joining 3 Tables In Laravel

I am using Laravel 7 and joining 3 tables for student exams. I have it working great except for the exam results column. It is pulling the first result it sees from the database and giving that same score to all the users. I am unsure how to write my joins in this instance. in my students table, I have the id and in my results table, I am trying to associate that id with the user_id. I ran a query in pypmyadmin and it gave the the results I was expecting SELECT * FROM oex_students INNER JOIN oex_results WHERE oex_students.id = oex_results.user_id However, in my controller, I am still unclear how to join in laravel. Here is my index controller:

public function index()
    {
        $data['portal'] = Oex_portal::get()->toArray();

        $data['exams'] = Oex_exam_master::where('status', '1')->get()->toArray();
        $data['result_info'] = Oex_result::select('oex_results.*', 'oex_results.result as result')
        ->get()->first();
        $data['students'] = Oex_students::select(['oex_students.*', 'oex_exam_masters.title as exam_name'])
        ->join('oex_results', 'oex_students.id', '=', 'oex_results.user_id')
        ->join('oex_exam_masters', 'oex_results.exam_id', '=', 'oex_exam_masters.id')
        ->get()
        ->toArray();


        $data['category'] = Oex_category::where('status', '1')->get()->toArray();
        $data['exams'] = Oex_exam_master::select(['oex_exam_masters.*', 'oex_categories.name as cat_name'])->join('oex_categories', 'oex_exam_masters.category', '=', 'oex_categories.id')->get()->toArray();
        return view('admin.dashboard', $data);
    }

and I am calling it in my blade as such:

@foreach($students as $key => $student)
                               <tr>
                                <td>{{ $key+1 }}</td>
                                <td>{{ $student['name'] }}</td>
                                <td>{{ $student['email'] }}</td>
                                <td>{{ $student['mobile_no'] }}</td>
                                <td>{{ $student['exam_name'] }}</td>
                                {{-- <td>{{ $student['result'] }}%</td> --}}
                                <td>{{ $result_info->result }} %</td>
                                {{-- <td>N/A</td> --}}


                                @if($student['status']== 1)
                               <td><input data-id="{{ $student['id'] }}" class="student_status" type="checkbox" name="status" checked></td>
                                @else
                                <td><input data-id="{{ $student['id'] }}" class="student_status" type="checkbox" name="status"></td>
                                @endif

                               </tr>
                            @endforeach

If anybody can help me with my join statement, I would surely appreciate it. Thank you in advance.

Edit: When running dd($data['students']); I get:

array:3 [▼
  0 => array:11 [▼
    "id" => 14
    "name" => "John Stuwart"
    "email" => "[email protected]"
    "mobile_no" => "123456"
    "category" => null
    "exam" => "4"
    "password" => "y$SDsj/k0bizRRSi29ZL3K3erW3ljl2LpLmqBQ4pbTRzj1aDnGD5v8q"
    "status" => "1"
    "created_at" => "2020-11-23T18:06:29.000000Z"
    "updated_at" => "2020-11-23T18:06:29.000000Z"
    "exam_name" => "Business English Placement Test"
  ]
  1 => array:11 [▼
    "id" => 15
    "name" => "Guillermina Ramos Ambriz"
    "email" => "[email protected]"
    "mobile_no" => "+525517043338"
    "category" => null
    "exam" => "4"
    "password" => "y$UNohJhCMJyAU5Wl/MS44mONaopQ/clBsFTyZqZ3A6tGJrgsCkjIIu"
    "status" => "1"
    "created_at" => "2020-11-23T18:12:49.000000Z"
    "updated_at" => "2020-11-23T18:12:49.000000Z"
    "exam_name" => "Business English Placement Test"
  ]
  2 => array:11 [▼
    "id" => 16
    "name" => "Carlos Olivares"
    "email" => "[email protected]"
    "mobile_no" => "3601234567"
    "category" => null
    "exam" => "4"
    "password" => "y$hhLNxeEGIsuCwqxhUv1RL.MUIjSIBmK0pwg6hPEJavY79qiJK2U.S"
    "status" => "1"
    "created_at" => "2020-11-23T18:17:24.000000Z"
    "updated_at" => "2020-11-23T18:17:24.000000Z"
    "exam_name" => "Business English Placement Test"
  ]
]
Nov
03
3 weeks ago
Activity icon

Replied to Send Email For Password Reset With Laravel 5.5

@snapey Hello. I am having a hell of a time with this one as well. I keep getting back an empty response. Any hints would be appreciated. Thanks

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=Myeversosecretpassword
MAIL_ENCRYPTION=ssl
[email protected]
MAIL_FROM_NAME="${APP_NAME}"

I've tried tls ssl 465 25. and still I get the following:

Swift_TransportException
Expected response code 220 but got an empty response

P.S. I tried it with mailtrap and that worked but doesn't really help when I want to send the user a real email, right?

Edit

OK. The solution is not code related but rather adding an app password through gmail after 2 step authentication. Only then did my code word. I simply had to replace myeversosecretpassword with the gmail app password.

Oct
09
1 month ago
Activity icon

Replied to Can Login With Plain Text Password But Not Hashed.

Thanks for pointing me in the right direction @jlrdw , @martinbean . I was able to fix it with the following:

public function login_sub(Request $request)
    {
        // $portal = Oex_portal::where('email', $request->email)->where('password', $request->password)->get()->toArray();

        $portal = Oex_portal::firstWhere('email', $request->input('email'));
        // Hash::check($request->input('password'), $portal->password);
        // dd($portal->status);

        if ($portal) {

            if ($portal->status == 1 && password_verify($request->password, $portal->password)) {
                // $request->session()->put('portal_session', $portal[0]['id']);
                $request->session()->put('portal_session', $portal->id);

                return redirect('portal/dashboard');
            } else {
                return redirect('portal/login')->with('error', 'Your account is not active. Please contact your administrator.');
            }
        } else {
            return redirect('portal/login')->with('error', 'Your Email or Password is incorrect.');
        }
    }

It was the way I was using [''] in the code that was messing things up. Thanks again for your help.

Activity icon

Replied to Can Login With Plain Text Password But Not Hashed.

I think the problem is with the status check. I tried the following without the status check and received "true" but when I included the status check, I received "false". Any clues? Thank you.

if ($portal) {
    if (Hash::check($request->input('password'), $portal->password) && $portal[0]['status'] == 1) {
                dd("true");
            } else {
                dd("false");
            }
Activity icon

Replied to Can Login With Plain Text Password But Not Hashed.

So, I got a bit further but no joy. I should mention that Oex_portal is a teachers portal which house their name, id, email and password. Here is what I have so far, but I get the "Your account is not active error"

 public function login_sub(Request $request)
    {
        // $portal = Oex_portal::where('email', $request->email)->where('password', $request->password)->get()->toArray();

        $portal = Oex_portal::firstWhere('email', $request->input('email'));

        if ($portal) {
            if ($portal[0]['status'] == 1) {
                Hash::check($request->input('password'), $portal->password);

                $request->session()->put('portal_session', $portal[0]['id']);
                return redirect('portal/dashboard');
            } else {
                return redirect('portal/login')->with('error', 'Your account is not active. Please contact your administrator.');
            }
        } else {
            return redirect('portal/login')->with('error', 'Your Email or Password is incorrect.');
        }
    }

Also, I should mention that all the status's are set to 1 in the db.

Activity icon

Replied to Can Login With Plain Text Password But Not Hashed.

Thank you @martinbean . Luckily, I am in development still so no real risk yet. But yes, I will give it a try and report back.

Activity icon

Replied to Can Login With Plain Text Password But Not Hashed.

Hello @jlrdw . How do I go about doing that in this code? I'm a little lost. Thank you. In my db, I have hashed and plain text passwords.

Activity icon

Started a new Conversation Can Login With Plain Text Password But Not Hashed.

I have an application where when I started, I was using plain text passwords. I can use those same passwords for loggging in. Since, I have implemented hashed passwords using Laravels Hash::make. I cannot login using the hashed passwords, only plain text. I would like to know how to check within my existing code, the hashed passwords. I have gone over the docs but quite frankly, don't know how to implement what I found relating my my specific code (ie, I am still learning Laravel haha). Any help would be greatly appreciated. Thank you in advance. Here is the function:

public function login_sub(Request $request)
    {
        $portal = Oex_portal::where('email', $request->email)->where('password', $request->password)->get()->toArray();
        dd($portal);
        if ($portal) {
            if ($portal[0]['status'] == 1) {
                $request->session()->put('portal_session', $portal[0]['id']);
                return redirect('portal/dashboard');
            } else {
                return redirect('portal/login')->with('error', 'Your account is not active. Please contact your administrator.');
            }
        } else {
            return redirect('portal/login')->with('error', 'Your Email or Password is incorrect.');
        }
    }
Oct
07
1 month ago
Activity icon

Replied to Unable To Post Without Get Error Laravel 7

It worked. Thank you

Activity icon

Started a new Conversation Unable To Post Without Get Error Laravel 7

This is somthing that has concerned me for some time coming from a security standpoint, I am working on an application and every time I try to set up a post route, I get the error that the get method is not supported. Supported methods: Post. There is something here I am not getting and would sure appreciate some help understanding what is happening to get around this error. If I use get in my route, the data gets submitted to the database but I always heard that using a get request opens the door to potential security issues. Here is my form:

<form action="{{ url('portal/signup_sub') }}" class="">
            {{ csrf_field() }}
        {{ method_field('post') }}
            <div class="signUp-form">
                <div class="row">
                    <div class="col-sm-12">
                        <div class="form-group">
                            <label for="name">Enter Name</label>
                            <input type="text" name="name" class="form-control" placeholder="Enter Name">
                        </div>
                        <div class="form-group">
                            <label for="name">Enter Email</label>
                            <input type="email" name="email" class="form-control" placeholder="Enter Email">
                        </div>
                        <div class="form-group">
                            <label for="name">Enter Phone Number (optional)</label>
                            <input type="text" name="mobile_no" class="form-control" placeholder="Enter Phone Number">
                        </div>
                        <div class="form-group">
                            <label for="name">Enter Password</label>
                            <input type="password" name="password" class="form-control" placeholder="Enter Password">
                        </div>
                        <div class="form-group">
                            <button class="btn btn-success">Sign Up</button>
                        </div>
                        <div class="col-sm-12">
                            <h5 class="text-center">Already have an account? <a href="#">Login</a></h5>
                        </div>
                    </div>
                </div>
            </div>
        </form>

Edit: Forgot to add my PortalController. Here it is.

public function portal_signup()
    {
        return view('portal.signup');
    }

    public function portal_signup_sub(Request $request)
    {
        dd($request->all());
        return "I am sign up submission";
    }

and Here is my Route.

Route::get('portal/signup', '[email protected]_signup');
Route::post('portal/signup_sub', '[email protected]_signup_sub');

Any help would be greatly appreciated. Thank you.

Sep
29
1 month ago
Activity icon

Replied to Laravel Asset() Helper Function Not Working On Live Server

I am using a ubuntu droplet I set up under digital ocean. this one image is the only image that is not showing up. Every other image is showing up just fine. the only difference is that the static images are in the public/images/ folder and this one static image I am looking for in in the public/icons/ folder

Edit: Linux didn't want to look into my /icons/ folder so I copied the contents into the /img/ folder and changed the show.blade.php route to reflect that and it is now working. I hope this helps anyone else with this specific issue.

Activity icon

Replied to Laravel Asset() Helper Function Not Working On Live Server

Thank you for your reply @Snapey. I implemented what you suggested and it did make a change in the url I see in the chrome inspection tools. I still don't see the icon. So, maybe I (like a lot of others) don't have something set properly in the document root. Which is strange as my other assets from img within the public folder are appearing just fine in the live site. Any clues? Thank you.

<img src="{{ asset("/icons/{$extension}.jpg") }}" class="image-fluid w-25">

Is what I used.

<img src="http://178.128.190.243/icons/pdf.jpg" class="image-fluid w-25">

Is what shows up in the inspection tool.

Activity icon

Replied to Laravel Asset() Helper Function Not Working On Live Server

This may seem obvious to those who are seasoned Laravel users but I too am struggling with the same issue. With the exception that i am calling a variable within my src. All my other images are being pulled in just fine. However, what does one do in the case where

 <a data-toggle="" href="/storage/upload/{{ $images[$i]['name'] }}" target="_blank">
     <!-- <img src="{{ "/icons/{$extension}.jpg" }}" class="image-fluid w-25"> -->
      <img src="{{ asset(`/icons/{$extension}.jpg`) }}" class="image-fluid w-25">
  </a>

Works on local (both commented and uncommented) but not on my live server?

Activity icon

Replied to How Can I Display An Icon Depending On File Type In The View?

Great @MichalOravec. I only had to add the icons folder with the images, and give the else an a tag to the file and boom. Worked like a charm. Thank you.

Activity icon

Replied to How Can I Display An Icon Depending On File Type In The View?

Hello jlrdw and thank you for the response. In my case, how would that translate into an conditional. I assume this can be done within the code I have presented but I am unclear to go about it. Would I use an @if? Even though my variable is set to $image, I have allowed for any file type between img, png, pdf, docx etc.

Activity icon

Started a new Conversation How Can I Display An Icon Depending On File Type In The View?

Hello and thank you for taking the time to help me with my question. I have a task application which is working great. When you upload images, you can see their thumbnails and even click on them and be directed to a new tab to view the images at 100%. The problem is that when a client uploads a pdf, the icon shows up as a broken image icon. This makes sense as the img tag within the a tag obviously is an image icon.

My question is how can I indicate in my show.blade.php that it is an image when it is an image and a pdf or dox when it is a pdf or doc? Like I said, the app is working so the only code I am concerned with is the following (unless I am mistaken, please let me know):

...
<a data-toggle="" href="/storage/upload/{{ $images[$i]['name'] }}" target="_blank">
    <img src="/storage/upload/{{ $images[$i]['name'] }}" class="image-fluid w-50">
 </a>

               </div>
               @endfor
               @else
               <p class="ml-3 mb-1">No files found</p>
               @endif

           </div>

I am looking for something like: If file type is img (of any type) display the image thumb, if not, display an icon that represents "file".

Any help on this would be greatly appreciated. Thank you in advance.

Sep
20
2 months ago
Activity icon

Replied to Unclear On How To Delete Single Image From Post From Multiple Images

Hello @jeromefitzpatrick . I implemented the code you sent and it works great. The only problem left (related) is that after implementing it, yes it deletes form the db and storage, but now I cannot display the images as Laravel complains with the message Property [name'] does not exist on this collection referring to the line in show.blade.php <img src="/storage/upload/{{$images->name}}"> Any clues? Thanks mate. EDIT changed {{$images->name}} to {{ $images[$i]['name'] }} and now all is good. Thank you

Activity icon

Replied to Unclear On How To Delete Single Image From Post From Multiple Images

Thank you for your reply @jeromefitzpatrick . I will try to implement it tonight. I will keep you posted. Thank you.

Sep
19
2 months ago
Activity icon

Replied to Unclear On How To Delete Single Image From Post From Multiple Images

Hello and thanks for the response @jlrdw Should I create a separate function for this? I'm unclear as my app doesn't like my new function in the same controller.

Activity icon

Started a new Conversation Unclear On How To Delete Single Image From Post From Multiple Images

Using Laravel 7, I can upload, add and delete all images from a task (post if it were a blog) but I am unclear on how to delete a single image from a task view (single post view). I am using resource controller for tasks but I assume I will need a different function. I created one in the same TasksController and about the resource controller, I created a delete route for it. My application complains that I am trying to get a property 'task_name' of non object when I click the single image delete button. I am not sure how to go about this or if I need to create an Image Controller (of which I am not using at the moment). I will show what I am attempting and maybe, you can tell me if I am off base or share some recommendations. So, to start off with, here is my web.php:

<?php

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', '[email protected]')->name('home');

Route::get('/users', '[email protected]');
Route::delete('delete-image', '[email protected]')->name('delete-image');

Route::resource('tasks', 'TasksController');
Route::resource('users', 'UsersController');

My TasksController showing both my destroy method as well as my newly created delete method:

public function destroy($id)
    {
        $task = Task::with('images')->findOrFail($id);

        foreach ($task->images as $image) {
            Storage::disk('public')->delete('upload/' . $image->name);
        }

        $task->images()->delete();
        $task->delete();
        return redirect('home')->with('success', 'Task Deleted');
    }

    public function delete($id)
    {
        //
        $task = Task::with('images')->findOrFail($id);
        $task->images()->delete();

        $images = Image::find($id);
        Storage::disk('public')->delete('upload/' . $images->name);
        $images->name()->delete();
        return redirect('home')->with('success', 'Task Deleted');
    }

In my show.blade.php which would act as a single post view:

<div class="col-md-12">
                <h5>Images</h5>
                <hr />
                  <div class="row">
                      @if($task->images->count()>0)

                          @for($i=0; $i < count($images = $task->images()->get()); $i++)
                          <div class="col-lg-4 col-md-6 col-sm-12">
                            <a href="delete-image" class="badge badge-danger p-2 mb-3">Delete</a><br>
                            <a href="#" class="thumbnail" data-toggle="modal" data-target="#lightbox"><img class="w-50 mb-2" src="/storage/upload/{{ $images[$i]['name'] }}" alt=""></a>

                        </div>

                          @endfor
                          @else
                              <p>No images found</p>
                      @endif
                  </div>
                <br />
              </div>

In my Image.php Model my relationships are as follows:

public function task()
    {
        return $this->belongsTo('App\Task', 'task_id');
        // return $this->belongsTo(Task::class);
    }

    public static function boot()
    {
        parent::boot();
        self::deleting(function ($images) {

            // File::delete(Storage::path($images['name']));
            File::delete(str_replace('\', '/', storage_path('app/public/upload/' . $images->name)));
        });
    }

and in my Task.php Model:

public function images()
    {
        // return $this->hasMany('App\Image');
        return $this->hasMany(Image::class);
    }

    public static function boot()
    {
        parent::boot();
        self::deleting(function ($task) {
            foreach ($task->image ?: [] as $image) {
                $image->delete();
            }
        });
    }

If I missed anything, please let me know so I can modify my question. I really appreciate the help on this as I am a week behind. Thank you in advance.

Activity icon

Replied to Laravel 7 Image Not Deleting From Disk But Is Deleted From Db

Your answer helped set me down the path with renaming my images relationship. And @newbie360 got me the rest of the way. Thank you to both. I wish there were a way to mark 2 answers as the best.

Activity icon

Replied to Laravel 7 Image Not Deleting From Disk But Is Deleted From Db

Bloody well done. Thank you so much. 1 week lost on this issue. Many Thanks to you, @snapey, @jlrdw for helping me out with this. I have learned so freaking much this week so I guess it wasn't a total loss. Thanks a million.

Activity icon

Replied to Laravel 7 Image Not Deleting From Disk But Is Deleted From Db

I wish it were true. It works for the db and on the screen but not the disc. no errors. It just doesn't touch the disk.

Activity icon

Replied to Laravel 7 Image Not Deleting From Disk But Is Deleted From Db

Hello @NEWBIE360. Thank you for your help. I am getting closer. When I run a dd on the storage path plus $image->name I get

"C:\laragon\www\taskapp\storage\app/public/upload/1600536086-AICerikRobles4.png"

Which is one of the file names. I am still missing something. I employed the changes you suggested. Can it be that the / and the \ in the path name are messing things up? Here is my new destroy method:

 public function destroy($id)
    {
        // $task = Task::findOrFail($id);
        $task = Task::with('images')->findOrFail($id);

        // $images = Image::find($id);

        // $images = $task->images($id)->get();

        foreach ($task->images as $image) {
            dd(storage_path('app/public/upload/' . $image->name));
            Storage::delete(storage_path('app/public/upload/' . $image->name));
        }

        $task->images()->delete();
        $task->delete();
        return redirect('home')->with('success', 'Task Deleted');
    }

I should point out that I have two or three images in this task (post if it were a blog).

Sep
18
2 months ago
Activity icon

Replied to Laravel 7 Image Not Deleting From Disk But Is Deleted From Db

Good Idea. I will dig deeper. Thank you for your patience. Both you and @jlrdw

Activity icon

Replied to Laravel 7 Image Not Deleting From Disk But Is Deleted From Db

It comes back as null and when I run dd($task->image) it gives me back the array. so my question is, how do I access that in my Controller to delete all the images that belong to that particular task?

Activity icon

Replied to Laravel 7 Image Not Deleting From Disk But Is Deleted From Db

Thank you @jlrdw. It got rid of the error and I am still able to delete them from the db but the following code does not delete them from the disk. How frustrating. What am I possibly missing. Any help greatly appreciated.

 public function destroy($id)
    {
        $task = Task::findOrFail($id);
        $images = Image::find($id);

        foreach ((array) $images as $image) {
            File::delete('storage/app/public/upload/', $image->name);
        }


        $task->delete();
        return redirect('home')->with('success', 'Task Deleted');
    }
Activity icon

Replied to Laravel 7 Image Not Deleting From Disk But Is Deleted From Db

OK. I got the following after running some tests:

>>> File::delete('storage/app/public/upload/'.$image->name);
=> true

resulted in true and the file was deleted from my disk. My next dilemma is how to delete them all as most of my tasks(posts) have 3 or more images. If I try the same thing in my Controller, I get Property [name] does not exist on this collection instance

Sep
17
2 months ago
Activity icon

Replied to Laravel 7 Image Not Deleting From Disk But Is Deleted From Db

So, I have changed the storage folder and it is now showing up in the two locations like one would expect. In my main app public/storage/upload I have all the uploaded files that are also in the db as well as in storage/app/public/upload that the symlink refers to contain all the same files. In my TasksController, I changed the if statement to the following:

 if ($request->hasFile('images')) {
            $files = $request->file('images');
            foreach ($files ?: [] as $file) {
                $name = time() . '-' . $file->getClientOriginalName();
                $name = str_replace(' ', '-', $name);
                $file->storeAs('public/upload', $name);
                $task->image()->create(['name' => $name]);
                $images = new Image;
                $images->name = $name;
            }

This is what made the folder structure better as per @Snapey 's suggestion. I still am having a problem in my delete call as I am not sure how to create that method. If I use $task->image I don't get an error and the db gets deleted but the disk does not. If I use $image->name I get an error:

Property [name] does not exist on this collection instance.

Here is my destroy method (which I am sure is all messed up)

public function destroy($id)
    {
        $task = Task::findOrFail($id);
        $image = Image::all();
        $name = $task->image;

        File::delete('public/upload', $name);


        $task->delete();
        return redirect('home')->with('success', 'Task Deleted');
    }

Any help on this would be greatly appreciated. Thank you.

Activity icon

Replied to Laravel 7 Image Not Deleting From Disk But Is Deleted From Db

Yes, I am using a symlink but what I find strange is that I don't see task-images in the storage/app/public folder. I would assume as I have seen in other projects that there would be those files there and in my public folder as well. Maybe I am wrong.

Activity icon

Replied to Laravel 7 Image Not Deleting From Disk But Is Deleted From Db

In my case they are not sensitive images so I don't really think it matters at this point weather they are accessible to the public or not.

Activity icon

Replied to Laravel 7 Image Not Deleting From Disk But Is Deleted From Db

Thank you @Snapey. This is strange as I am looking in the public folder and in that is the task-images folder and in that I have 1600371770-egypt2.jpg which corresponds to id 74 name: "1600371770-egypt2.jpg", which is in my db. I am scratching my head on this one. Let me dig a bit deeper and comment tomorrow if I have luck or not. Thank you @Snapey. If you think of anything in the meantime, I certainly do appreciate it.

Activity icon

Replied to Laravel 7 Image Not Deleting From Disk But Is Deleted From Db

Here is the new result failing but at least I got the right id number:

>>> $image = Image::find(74);
=> App\Image {#4121
     id: 74,
     name: "1600371770-egypt2.jpg",
     task_id: 24,
     created_at: "2020-09-17 19:42:50",       
     updated_at: "2020-09-17 19:42:50",       
   }
>>> Storage::delete('task-images/'.$image->name);
=> false
>>>

Could it be that I am trying to delete an array of objects at the same time but unclear on how to go about it?

Activity icon

Replied to Laravel 7 Image Not Deleting From Disk But Is Deleted From Db

Here is what I get after the first Tinker test:

$ php artisan tinker
Psy Shell v0.10.4 (PHP 7.3.0 — cli) by Justin 
Hileman
>>> $image = Image::find(1);
[!] Aliasing 'Image' to 'App\Image' for this Tinker session.
=> null
>>> Storage::delete('task-images/' . $image->name);
PHP Notice:  Trying to get property 'name' of 
non-object in Psy Shell code on line 1        
=> false
>>>

So, I obviously have something wrong or am clueless on how to access my disk. the db gets deleted just fine but the storage disk remains intact.

If I run $image = Image::all('name'); and run a dd($image); I get:

Illuminate\Database\Eloquent\Collection {#1217 ▼
  #items: array:7 [▼
    0 => App\Image {#1218 ▼
      #fillable: array:2 [▶]
      #uploads: "/task-images/"
      #connection: "mysql"
      #table: "images"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:1 [▼
        "name" => "1600371770-egypt2.jpg"
      ]
      #original: array:1 [▶]
      #changes: []
      #casts: []
      #classCastCache: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [▶]
    }
    1 => App\Image {#1219 ▶}
    2 => App\Image {#1220 ▶}
    3 => App\Image {#1221 ▶}
    4 => App\Image {#1222 ▶}
    5 => App\Image {#1223 ▶}
    6 => App\Image {#1224 ▶}
  ]
}
Activity icon

Replied to Laravel 7 Image Not Deleting From Disk But Is Deleted From Db

Thank you @Snapey . I will give that a shot and report back. Thank you @jlrdw , I will make a back up first.

Activity icon

Replied to Laravel 7 Image Not Deleting From Disk But Is Deleted From Db

I am using, I belive the foreign key of task_id in the image model to relate to the task model:

 Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->string('name')->default('image.png')->nullable();
            $table->unsignedBigInteger('task_id');
            // $table->string('image_path');
            $table->timestamps();
        });
Activity icon

Replied to Laravel 7 Image Not Deleting From Disk But Is Deleted From Db

thank you @jlrdw and @sinnbeck. I have tried with both th unlink option and changing the delete option you guys provided. No joy yet. I tried using $image->name but that threw an error so I tried with $task->image and ran a dd on that request. This is what I got in return: "task-images/[{"id":64,"name":"1600350578-newEgypt.jpg","task_id":22,"created_at":"2020-09-17T13:49:38.000000Z","updated_at":"2020-09-17T13:49:38.000000Z"},{"id":65,"name":"1600350578-scifi1.jpg","task_id":22,"created_at":"2020-09-17T13:49:38.000000Z","updated_at":"2020-09-17T13:49:38.000000Z"},{"id":66,"name":"1600350578-scifi1.webp","task_id":22,"created_at":"2020-09-17T13:49:38.000000Z","updated_at":"2020-09-17T13:49:38.000000Z"}] ◀"

Activity icon

Started a new Conversation Laravel 7 Image Not Deleting From Disk But Is Deleted From Db

I am able to successfully add multiple images for the task (post if it were a blog) and delete the task. The task is successfully deleted from the db as well as its subsequent images. However, in the disc (by the way, I am working local at the moment) the files remain untouched. I am unsure how to handle this request as I am new to Laravel. Any help would be greatly appreciated. Here is what I have in my various files. TaskController.php showing both my store and delete functions:

public function store(Request $request)
    {
        $this->validate($request, [
            'task_name' => 'required',
            'task_description' => 'required',
        ]);

        // Create Task
        $user = Auth::user();
        $task = new Task();
        $data = $request->all();
        $task->user_id = $user->id;
        $task = $user->task()->create($data);
        if ($request->hasFile('images')) {
            $files = $request->file('images');
            foreach ($files ?: [] as $file) {
                $name = time() . '-' . $file->getClientOriginalName();
                $name = str_replace(' ', '-', $name);
                $file->move('task-images', $name);
                $task->image()->create(['name' => $name]);
                $images = new Image;
                $images->name = $name;
            }
        }
        $task->task_name = $request->input('task_name');
        $task->task_description = $request->input('task_description');
        $task->task_priority = $request->input('task_priority');
        $task->task_assigned_by = $request->input('task_assigned_by');
        $task->task_assigned_to = $request->input('task_assigned_to');
        $task->task_to_be_completed_date = $request->input('task_to_be_completed_date');
        $task->task_notes = $request->input('task_notes');
        $task->task_status = $request->task_status;
        $task->save();



        return redirect('/home')->with('success', 'Task Created');
    }

public function destroy($id)
    {
        $task = Task::findOrFail($id);
        $task->delete();
        return redirect('home')->with('success', 'Task Deleted');
    }

Where I am attempting to delete is in my show.blade.php (just the delete form)

<form style="display: inline;" action="/tasks/{{ $task->id }}" method="POST" class="">
              @csrf
              @method('DELETE')
            <button type="submit" class="btn btn-danger btn-sm ml-1 mr-1">
              <i class="fa fa-trash"></i> Delete
            </button>
 </form>

In my web.php, I am using a resource controller for TasksController.php.

In my Image.php Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
use App\Task;

class Image extends Model
{
    protected $fillable = [
        'task_id',
        'name',
    ];

    protected $uploads = '/task-images/';

    public function getFileAttribute($image)
    {
        return $this->uploads . $image;
    }


    public function task()
    {
        // return $this->belongsTo('App\Task', 'task_id');
        return $this->belongsTo(Task::class);
    }

    public static function boot()
    {
        parent::boot();
        self::deleting(function ($image) {
            Storage::delete(Storage::path($image->name));
        });
    }
}

and my Task.php Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Image;
use Illuminate\Support\Facades\Storage;


class Task extends Model
{
    protected $fillable = [
        'task_name', 'task_priority', 'task_assigned_to', 'task_assigned_by', 'task_description', 'task_to_be_completed_date', 'task_status',
        'task_notes'
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function image()
    {
        // return $this->hasMany('App\Image');
        return $this->hasMany(Image::class);
    }

    public static function boot()
    {
        parent::boot();
        self::deleting(function ($task) {
            foreach ($task->image ?: [] as $image) {
                $image->delete();
            }
        });
    }
}

Finally, in my filesystem.php, for the disk section, I have:

'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

If I have missed something, please let me know and I will edit my question. Thank you in advance for your help.

Sep
08
2 months ago
Activity icon

Replied to Uploading Multiple Files Not Passing Foreach

Hello @snapey. I am getting the same issue. I ran the dd($uploadedFiles) which is the name I am using in my case and my dd came back null. Which I would expect since this is the first image. I am using Laravel 7. Anything change since the 5.4 Laravel version that would point me in the right direction? Thanks.

Aug
31
2 months ago
Activity icon

Replied to Unable To Delete Record As Authenticated User (vendor)

Hello Loyd and Snapey. Thank you for your reply. I figured out the problem and I appologize for not posting my web.php. In that, I had not correctly wrapped my route groups. I had my vendor outside of the vendor group thus anything it did that had any impact on the admin was denied. Here is my web.php now that I fixed it.

Route::get('/', function () {
    return view('frontend.index');
  });


Auth::routes();

Route::group(['middleware' => ['auth', 'isAdmin']], function () {
    Route::get('/dashboard', function () {
        return view('admin.dashboard');
    });

    // Usuarios
    Route::get('registered-user', 'Admin\[email protected]');
    Route::delete('/user-delete/{id}', 'Admin\[email protected]');
    Route::get('role-edit/{id}', 'Admin\[email protected]');
    Route::put('role-update/{id}', 'Admin\[email protected]');
    // Empresas
    Route::get('registered-empresa', 'Admin\[email protected]');
    Route::post('save-empresa', 'Admin\[email protected]');
    Route::get('/edit-empresa/{id}', 'Admin\[email protected]');
    Route::put('/empresa-update/{id}', 'Admin\[email protected]');
    Route::delete('/delete-empresa/{id}', 'Admin\[email protected]');
    // Empleados
    Route::get('registered-empleado', 'Admin\[email protected]');
    Route::get('/edit-empleado/{id}', 'Admin\[email protected]');
    Route::put('/empleado-update/{id}', 'Admin\[email protected]');
    Route::post('save-empleado', 'Admin\[email protected]');
    Route::delete('/delete-empleado/{id}', 'Admin\[email protected]');
  });

Route::group(['middleware' => ['auth', 'isVendor']], function () {
    Route::get('/vendor-dashboard', function () {
        return view('vendor.dashboard');
    });

    Route::resource('vendor-empresas', 'vendorEmpresaController');
    Route::delete('/vendor-empresas/{vendor_empresa}', '[email protected]');

    Route::resource('vendor-empleados', 'vendorEmpleadoController');
    Route::get('vendor-profile', 'Vendor\[email protected]');
    Route::post('vendor-profile-update', 'Vendor\[email protected]');
  });

Route::group(['middleware' => ['auth', 'isUser']], function () {

    Route::get('/home', '[email protected]')->name('home');
    Route::get('my-profile', 'Frontend\[email protected]');
    Route::post('my-profile-update', 'Frontend\[email protected]');
  });

Thank you for your replies.

Aug
24
3 months ago
Activity icon

Started a new Conversation Unable To Delete Record As Authenticated User (vendor)

I have a role_as vendor and want to delete one of the authenticated user's records. I get redirected to the admin home (which I am not authorized to view which is correct) and the record does not get deleted. I have tried Policies and middleware but unable to get this to work. In my destroy function, I have:

public function destroy($id)
    {

        $empresa = Empresa::find($id);
        $this->authorizeResource(Empresa::class, 'delete', $empresa);
        if ($empresa != null) {
            $empresa->delete();
            return redirect('/vendor-empresas')->with('status', 'Empresa Borrado Exitosamente.');
            // return redirect()->to('/vendor-empresas')->with('status', 'Empresa Borrado Exitosamente.');
        } else {
            return redirect('/vendor-empresas')->with('status', 'ID Equivocado! La empresa no fue borrado.');
        }
    }

My index.blade.php delete form:

 <form action="vendor-empresas/{vendor_empresa}" method="POST" id="deleteForm">
        {{ csrf_field() }}
        @method('delete')
      <div class="modal-body mx-3">
        <input type="hidden" name="_method" value="DELETE">
        <div class="text-center">
            <i class="fas fa-exclamation-triangle mb-4" style="color: #ffc107; font-size: 32px;"></i>
        </div>
            <h3 class="text-center text-uppercase">¿Estás Seguro/a?
        </h3>
      </div>
      <div class="modal-footer d-flex justify-content-center">
        <button class="btn btn-primary" data-dismiss="modal">Cancelar</button>
        <button type="submit" class="btn btn-danger">Sí, Borralo!</button>

      </div>
    </form>

AuthServiceProvider:

protected $policies = [
        'App\Empresa' => 'App\Policies\EmpresaPolicy',
    ];

Admin Middleware:

public function handle($request, Closure $next)
    {
        if (Auth::user()->role_as == 'admin') {
            return $next($request);
        } else {
            return redirect('/home')->with('status', 'You are not permitted to access the  Admin dashboard.');
        }
    }

the VendorMiddleware

 public function handle($request, Closure $next)
    {
        if (Auth::user()->role_as == 'vendor') {
            if (Auth::check() && Auth::user()->isBanned) {
                $banned = Auth::user()->isBanned == "1";
                Auth::logout();

                if ($banned == 1) {
                    $message = 'Your account has been Banned. Please contact the administrator.';
                }
                return redirect()->route('login')->with('status', $message)->withErrors(['email' => 'Your account has been Banned. Please contact the administrator.']);
            }
            return $next($request);
        } else {
            return redirect('/home')->with('status', 'You are not permitted to access the vendor dashboard, OK?');
        }
    }
}

I am able to view, create and edit but not delete. I am unsure what I am doing wrong as I am new to Laravel. Thank you in advance for any help you can provide.

Jul
12
4 months ago
Activity icon

Replied to Laravel Nova As Backend Catch All Routes

I would like to know this as well. Not a lot of Nova People out there yet.