How to make a page accessible even user is not logged in - php

I have a page which is a company page in which should be accessible even the user is not logged in. I am using blade template in which is called in all other pages. My problem now is I'm having an issue with this one:
<div class="profimg fitimg">
<img src="{{ Auth::user()->photo == null ? url('assets/images/profile.png') : Auth::user()->photo }}" alt="">
</div>
It will return an error
Trying to get property 'photo' of non-object (View: /var/www/resources/views/layouts/user/mypage.blade.php)
This part of my template gets the users profile photo. In my web.php, it looks like this:
Route::prefix('/')->group(function() {
Route::get('company', function () {
return view('user.company');
});
});
And I also have this if the user is logged in.
Route::group(['middleware' => 'auth:user'], function () {
//routes for auth user
});
My problem now is, how can I make a page accessible by public even though they are not logged in? And if they are logged in, I can get their profile info in my template. I think there's some sort of solution for this one but I just can't figure it out.

It is a good practice to pass the data instead of directly accessing a class. So, if you change the route to this -
Route::prefix('/')->group(function() {
Route::get('company', function () {
$data['user'] = Auth::user();
return view('user.company', $data);
});
});
The user item of data array should have some value if the user is logged in. Then you can check if user has any data and change your html like this-
<div class="profimg fitimg">
#if($user)
<img src="{{ $user->photo }}" alt="{{ $user->name }}">
#else
<img src="{{ url('assets/images/profile.png') }}" alt="default profile image">
#endif
</div>

Firstly, inside of laravel blade, you don't need to put php tags. You should use double curly brackets instead.
If you want to completely hide the image when a user is not logged in, you can try this:
#if(Auth::check())
<img src=" {{ Auth::user()->photo ?? url('assets/images/profile.png') }} ">
#endif
If you want to show the placeholder when the user is not logged in, or if no image has been set, try this:
#if(Auth::check() && !empty(Auth::user()->photo))
<img src=" {{ Auth::user()->photo }} ">
#else
<img src="{{ url('assets/images/profile.png') }}"
#endif

Related

Cannot find the way to make #if statement works in blade

I'm making a "teacher's" app, and I want to make a log-in page which changes depending if there's registered users in the database or not.
I want to make a redirection button to a create user page if there aren't auth users in database, and to make a select user view if the database have one or more users.
The problem is that I don't know how to exactly do this, 'cause the view always shows me the first statement (what I've got in the if), also if in the database are registered users. Can anyone help me with this please?
This is the blade file:
#if (empty(Auth::user()->id))
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Welcome</h1>
<p>We see there aren't users</p>
</div>
<div id="loginForm">
<button type="button" onclick="window.location='{{ url("/newUser") }}'">Button</button>
</div>
</div>
#else
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Select an user</h1>
</div>
<div id="loginForm"></div>
</div>
#endif
Here you have the controller index method:
public function index()
{
$users = User::all();
return view('/', compact('users'));
}
And finally here you have the page:
The following code is the sample for it, kindly replace code accordingly
#if(!$user)
//show button
#else
//dont show button
#endif
I think your question is you want to check if there is user in database.
So no need to check if the user authenticated but to check if there is user on the database.
In your controller
public function index() {
return view('/', ['users' => User::all()]);
}
and in your blade file
#if(!$users)
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Welcome</h1>
<p>We see there aren't users</p>
</div>
<div id="loginForm">
<button type="button" onclick="window.location='{{ url("/newUser") }}'">Button</button>
</div>
</div>
#else
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Select an user</h1>
</div>
<div id="loginForm"></div>
</div>
#endif
This function will get the current authenticated user: Auth::user(). I guess what you are trying to achieve is #if(empty($users)) where $users is the variable you are passing on controller.
If you want to verify if the user that accessed to that view is authenticated you can simply use #auth and #guest.
Also i would suggest you to change your button to an <a> tag and your href would be <a href="{{ route('route.name') }}" where route.name would be defined in your routes file.
in your controller:
you can create a folder inside views called users and then the index.blade.php (views/users/index.blade.php)
public function index()
{
$users = Users::all();
return view('users.index')->with('users', $users);
}
in your view:
#if(count($users) < 1)
...
#else
...
#endif
count is validating if the $users array length is less then 1 (in other words if the array is empty).
Alternative you can you isEmpty()
#if($users->isEmpty())
...
#else
...
#endif

Laravel edit dropzone

I saved files(images) by DropzoneJS and I can get them everywhere I like, but my problem is how to edit them. I go to my products edit page I can see my image but have no idea how to edit them such as (delete some of them or add to them)
here is my code to get them:
public function edit($id)
{
$product = Product::findOrFail($id);
$images = DB::table('images')->where('imageable_id', '=', $product->id)->get();
// rest of codes
}
and I show my images in edit page like:
#foreach($images as $test)
<img src="{{url('/')}}/images/{{$test->name}}" alt="test" width="100" height="100">
#endforeach
screenshot
UPDATE
#linktoahref way works for me if I want to delete each of images, and he suggested to make new uploader for adding images into my product on edit page, not bad idea totally but it's not what I'm exactly looking for.
What I try to achieve is to use DropZone itself to return my exist
images of each product and be able to remove or add to it.
I read many questions,articles, etc. And I get that I have to use mockFile which i have no idea about it. Would be appreciate if someone can help me to get this done.
Thanks.
For DELETE, you could add a button next to the image that would fire the destroy method of the respective controller
#foreach($images as $test)
<img src="{{ url('/') }}/images/{{ $test->name }}" alt="test" width="100" height="100">
<a href="#" class="btn btn-danger"
onclick="event.preventDefault();
document.getElementById('image-{{ $test->id }}').submit();">
DELETE
</a>
<form id="image-{{ $test->id }}"
action="{{ route('images.destroy', ['id' => $test->id]) }}"
method="POST" style="display: none;">
{{ csrf_field() }}
{{ method_field('DELETE') }}
</form>
#endforeach
and handle the deletion of image in your ImageController's destroy method (or your custom controller's method, make sure the method types are same)
public function destroy(Image $image)
{
// Destroy the Image
Storage::delete($image->name);
// Redirect Back
return redirect()->back();
}

Getting error when a user is not logged in because Auth::user()->hasRole('Admin')` can not check if the user has role of admin in Laravel

I have an a tag that works as a delete button for an image, however, in my blade template I display the button only to the uploader of the image or the admins of the website. Unfortunately, when a user is not logged, I get an error because Auth::user()->hasRole('Admin') can not check if the user has role of admin. Any idea how am I supposed to avoid this problem?
The error:
"Call to a member function hasRole() on null"
My code
<div class="wrapper">
<div class='imageContainer'>
<h1 class='imageTitle'>{{$image->name}}</h1>
<div class="stickyImageContainer">
<img class='uploadedRealImage' src='/storage/images/uploaded/{{$image->file_name}}' alt='Random image'/>
#if (Auth::id() === $image->user_id || Auth::user()->hasRole('Admin'))
<div class='deleteImageButton'></div>
<a class='deleteImageA' href='{{ route('deleteImage', ['image_id' => $image->id]) }}'>X</a>
#endif
</div>
</div>
</div>
You need to check if Auth::user() returned a model or just null first:
#if (Auth::id() === $image->user_id || (Auth::user() && Auth::user()->hasRole('Admin')))
It's probably cleaner to break these into two nested :
#if(Auth::user())
#if(Auth::id() === $image->user_id || Auth::user()->hasRole('Admin'))
or even better, use Laravel's authorization gates to encompass this logic, which will allow you to do:
#can('delete', $image)
Use auth()->check() prior to attempting to access the user's role.
#if(auth()->check() && Auth::user()->hasRole('Admin'))
....
#endif
Laravel also offers the can and cannot blade directives. See: https://laravel.com/docs/5.5/authorization#via-blade-templates

Laravel: Image not loading

I am trying to load an image in Laravel. The image is loading in a header.blade.php file. It is working fine on other pages but when it comes to localhost:8000/edit/id, It just doesn't work. I am loading Image like this:
<a href="{!! URL::to('/') !!}">
<img src="images/logo.png" />
</a>
My Route:
Route::get('edit/{id}', array('uses' => 'HomeController#edit'));
My Controller:
public function edit($id) {
$reg = Register::find($id);
$user = User::where('email', Session::get('email'))->first();
if ($reg->user_id == $user->id) {
return View::make('edit')
->with('id', $id);
} else {
return Redirect::to('dashboard')->with('wrong', 'Sorry! Something Went Wrong!');
}
}
My image directory: public/images/logo.png
It is working fine on other pages like localhost:8000/about but it doesn't work on localhost/edit/2, any help?
The problem is that when you are on your url, it is not looking for the image in the root folder of your application, but in the current location.
So when you are visiting localhost/edit/2, it is looking for the image in localhost/edit, instead of in localhost.
Try changing your code by adding a slash in the beginning of the image
<a href="{!! URL::to('/') !!}">
<img src="images/logo.png" />
</a>
to
<a href="{!! URL::to('/') !!}">
<img src="/images/logo.png" />
</a>
Additionally, you should actually try the laravel way, like this:
{{ HTML::image('images/logo.png', 'logo') }}
try
{{ HTML::image('images/logo.png', 'logo') }}
output will be like
<img src="http://your.url/images/logo.png" alt="logo">
also you can check image path using inspect element in browser
<img src="public/storage/cover_images/image_name.format" class="img-resposive">
it will load your picture otherwise check the path to image and previlages of the folders you can load image only from a public path due to security reasons

eloquent scope to eager load with constriant?

Ok so I'm trying to setup a scope that will restrict which users are returned based on a column in a hasOne relation.
Here are the two methods from my User model:
public function scopeHasImage($query)
{
return $query->with(['profile' => function($query){
$query->where('avatar', '!=', '');
}]);
}
public function profile()
{
return $this->hasOne('App\Profile');
}
When I call it like so:
$users = User::HasImage()->simplePaginate(15);
All of that works ok untill I go to display the code in my blade template like so:
#foreach($users as $user)
<div class="col-xs-12 col-sm-3 col-md-2">
<a href="{{ route('user.profile.public', ['id' => $user->id]) }}">
<img class="img-responsive" src="{{ $user->profile->avatar }}" />
</a>
</div>
#endforeach
That results in this error:
Trying to get property of non-object
I have dumped the $user->profile and it is an object which has attributes listed and one of those attributes is avatar. So I'm not sure why this is not working.
Any thoughts would be greatly appreciated.
Almost certainly one of your users has no profile attached. Because you probably dumped only the the first $user->profile you didn't see that...
You can fix this by wrapping it in an if:
#foreach($users as $user)
#if($profile = $user->profile)
<div class="col-xs-12 col-sm-3 col-md-2">
<a href="{{ route('user.profile.public', ['id' => $user->id]) }}">
<img class="img-responsive" src="{{ $profile->avatar }}" />
</a>
</div>
#endif
#endforeach
Or exclude users without a profile in the first place (which is probably what you wanted all along)
public function scopeHasImage($query)
{
return $query->with('profile')->whereHas('profile', function($query){
$query->where('avatar', '!=', '');
});
}

Categories