in my project I use Laravel 8, Livewire and Alpine.js.
My livewire toaster code (app\Http\Livewire\ToasterNotification.php):
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class ToasterNotification extends Component
{
public $notifications = array();
protected $listeners = ['notificationUpdate', 'notificationRemove'];
public function notificationUpdate($notif)
{
array_push($this->notifications, $notif);
$this->dispatchBrowserEvent('toast-message-show');
}
public function notificationRemove($id)
{
unset($this->notifications[$id]);
}
public function render()
{
return view('livewire.toaster-notification');
}
}
Which executes this blade (resources\views\livewire\toaster-notification.blade.php) and he will call a blade component named toaster on "x-toaster":
<div
wire:poll.5s
aria-live="polite"
aria-atomic="true"
style="z-index:1200; position: absolute; top: 70px; right: 20px; min-height: 200px;"
>
#foreach($notifications as $i => $notification)
<x-toaster id="{{ $i }}" message="{{ $notification['message'] }}" color="{{ $notification['color'] }}"/>
#endforeach
</div>
(resources\views\components\toaster.blade.php):
<div
class="toaster toastAlert show border-{{ $color }}"
style="min-width: 250px"
data-autohide="false"
role="alert"
aria-live="assertive"
aria-atomic="true"
id="toastAlert{{ $id }}"
>
<div class="toast-header">
<svg class="bd-placeholder-img rounded mr-2 bg-{{ $color }}" width="20" height="20" focusable="false" role="img">
<rect width="100%" height="100%" fill="#ffffff00"></rect>
</svg>
<strong class="mr-auto">{{ $message }}</strong>
<button type="button" class="ml-2 mb-1 close" wire:click="notificationRemove({{ $id }})">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
I want improve the old system which reloads every 5s and use alpine along livewire if possible.
Actually my code looks like this :
<script defer src="https://unpkg.com/alpinejs#3.9.0/dist/cdn.min.js"></script>
<style> [x-cloak] { display: none !important; } </style>
<div
x-data="{show:false}"
#toast-message-show.window="
show = true;
setTimeout(() => show=false, 5000);
"
x-show="show"
x-cloak
>
#foreach($notifications as $i => $notification)
<x-toaster id="{{ $i }}" message="{{ $notification['message'] }}" color="{{ $notification['color'] }}"/>
#endforeach
</div>
But I have no display. I think there is an issue because nothing is executed while in the foreach. I've tried to add some test messages like
<h1 x-data="{ message: 'I ❤️ Alpine' }" x-text="message"></h1>
But nothing worked out.
Ok i found out the answer, it was messy but i had to remove the style and put the src in the blade app.
Related
I'm having an issue that possibly a lot of people already had on here, but I can't seem to figure it out.
I'm trying to use Carbon and Paginate in the same variable, but keep getting the error shown in the title.
The code that I'm trying to use it with is:
Controller:
public function index()
{
$announcements = Announcement::withCount('replies')->orderBy('created_at', 'desc')->paginate(5);
$birthdays = User::whereRaw('DAYOFYEAR(curdate()) <= DAYOFYEAR(birthday) AND DAYOFYEAR(curdate()) + 365 >= dayofyear(birthday)')
->orderByRaw('DAYOFYEAR(birthday)')
->get();
$date = Carbon::create($announcements->created_at)->locale('nl');
return view('home', compact('announcements', 'birthdays', 'date'));
}
View:
#foreach($announcements as $announcement)
<div class="announcement">
<div class="row">
<div class="col-lg-11">
<h2 style="font-size:1.5rem;" class="text-capitalize">{{$announcement->post_title}}</h2>
#if($announcement->post_image == null)
#else
<img src="{{$announcement->post_image}}" style="width:100%;">
#endif
<p style="font-size: 0.8rem;">{{$birthday->isoFormat('LL')}} | Geplaatst door <span>{{$announcement->username}}</span> | <span style="color:#007ac3">{{$announcement->replies_count}} reacties</span></p>
<p style="margin-top: -10px; text-overflow: ellipsis; white-space: nowrap; overflow: hidden;">{!! Str::words($announcement->post_content, 20) !!}</p>
</div>
<div class="col-lg-1">
#if(Auth::user()->admin == 1)
<i class="fal fa-dumpster" style="text-align: center;position: relative;font-size: 20px;"></i>
#endif
</div>
</div>
<p>Meer lezen <i class="fas fa-angle-double-right"></i></p>
<hr>
</div>
#endforeach
I'm expecting it to translate the date to Dutch, but for now all I'm getting is the error.
The ->paginate() method returns a LengthAwarePaginator object, not a single model. You'll need to map the date function over each element in the Collection object.
I was trying to make that when there was a post made by user John whit user_id 1
It check if he has an profile and if he has an profile it puts the image next to it that corresponds to the user and the profile he or she created. so when I login whit the user it works fine because I'm getting the user id out of
Auth::user()->id
But when I log in whit another user and look at the page I get off an error.
Error:
Trying to get property 'id' of non-object (View:
C:\Users\Merlijn\AppData\Roaming\Composer\Laravel
Projects\blog\resources\views\posts\post.blade.php) (View:
C:\Users\Merlijn\AppData\Roaming\Composer\Laravel
Projects\blog\resources\views\posts\post.blade.php)
so mine question is How can I make that the Image that belongs to the user is connected to the post the user image and post are in 3 different tables.
here how I try to do it now?
Post.blade.php
<div class="blog-post">
<h2 class="blog-post-title">
<a href="{{ route('posts.show', ["post" => $post->id]) }}">
{{ $post->title }}
</a>
</h2>
<p class="blog-post-meta">
#foreach($image as $path)
#if(Auth::user()->id == $path->user_id)
{{--{{dd($path)}}--}}
#if(!$path->image_path == null)
<img src="/images/{{ $path->image_path }}" id="imgProfile" style="width: 150px; height: 150px" class="img-thumbnail" />
#else
<img src="http://placehold.it/150x150" id="imgProfile" style="width: 150px; height: 150px" class="img-thumbnail" />
#endif
#endif
#endforeach
{{ $post->user->name }} on
{{ $post->created_at->toFormattedDateString() }}
</p>
<p>
{{
$post->body
}}
</p>
<br>
#if (Auth::check())
#if(Auth::user()->id == $post->user_id)
<div class="button-box col-lg-12">
Edit
Delete
</div>
#endif
#endif
<hr>
AppService provider
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
use View;
use App\Profile;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Schema::defaultStringLength(191);
view()->composer('layouts.sidebar', function($view){
$view->with('archives', \App\Post::archives());
});
View::share('image', Profile::all());
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
}
If u need anything like extra information note it and I will edit it in
as Suborno said, you shouldn't use Auth::user()->id since this will always put the image of the logged in user there.
You want to link a user to the post with a one to many relationship and then you can use $post->user->id
https://laravel.com/docs/5.7/eloquent-relationships#one-to-many
class post extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
#foreach($image as $path)
#if($post->user->id == $path->user_id)
{{--{{dd($path)}}--}}
#if(!$path->image_path == null)
<img src="/images/{{ $path->image_path }}" id="imgProfile" style="width: 150px; height: 150px" class="img-thumbnail" />
#else
<img src="http://placehold.it/150x150" id="imgProfile" style="width: 150px; height: 150px" class="img-thumbnail" />
#endif
#endif
#endforeach
note: this all depends on how you have your models/database set up.
How are you expecting Auth::user()->id to work if you are not logged in?
Auth::user() only has the session data of the logged in user.
Change this condition #if(Auth::user()->id == $path->user_id) to something more suitable like (!empty) if you are willing to access multiple users data or without logging in at all.
Try with this
#foreach($image as $path)
#if(Auth::user()->id == $path->user_id)
#if(!$path->image_path == null)
<img src="/images/{{ $path->image_path }}" id="imgProfile" style="width: 150px; height: 150px" class="img-thumbnail" />
#else
<img src="http://placehold.it/150x150" id="imgProfile" style="width: 150px; height: 150px" class="img-thumbnail" />
#endif
#else
<img src="http://placehold.it/150x150" id="imgProfile" style="width: 150px; height: 150px" class="img-thumbnail" />
#endif
#endforeach
Hope this helps :)
I am using Laravel 5.6 and mysql for my web application. in My application I have table named as vehicles as following,
id name number adtype
----------------------------
1 car 123 1
2 van 256 0
3 car 248 0
4 van 159 1
5 car 158 1
etc
and I am displaying above data on VehicleController as following
public function index(){
$vehicles = Vehicle::with('uploads')->get();
return view('vehicles.index')->withVehicles($vehicles);
}
upload is related table witch contain images of the vehicles
and My index.blade.php is like this
<div class="col-md-7 col-md-offset-1">
#forelse( $vehicles as $vehicule )
#if( $vehicule->uploads->count() > 0 )
<a href="{{ route('vehicles.show', $vehicule->id) }}">
#php
$upload = $vehicule->uploads->sortByDesc('id')->first();
#endphp
<div style="border-style: solid; color: black; ">
<img src="/images/{{ $upload->resized_name }}" height="150" width="250"></a>
#endif
</div>
it is working fine. but now I need highlight ads which related to adtype value as 1 from the vechicles table. how can do it?
I'm not entirely sure if I get your question right, but where's the problem of just using an if to determine if adtype equals 1 and handle the div's class or style attribute differently?
<div style="color: {{ $vehicule->adtype === 1 ? 'black' : 'blue' }}">
Besides that: You shouldn't lazy load something in a template; that's not the purpose of the template, this is a task for the controller. Use eager loading with a proper relation instead.
Note: You can - or should - also type cast attributes to equal their original purpose and prevent misleading comparisons.
In your case adtype looks like a boolean, so you would add this to your model's $cast property:
'adtype' => 'boolean',
try
<div class="col-md-7 col-md-offset-1">
#forelse( $vehicles as $vehicule )
#if( $vehicule->uploads->count() > 0 )
<a href="{{ route('vehicles.show', $vehicule->id) }}">
#php
$upload = $vehicule->uploads->sortByDesc('id')->first();
#endphp
#if($vehicule->adtype == 1)
<div style="border-style: solid; color: black; ">
<img src="/images/{{ $upload->resized_name }}" height="150" width="250"></a>
</div>
#else
<div style="border-style: solid; color: blue; ">
<img src="/images/{{ $upload->resized_name }}" height="150" width="250"></a>
</div>
#endif
#endif
</div>
I'm not sure I understand all of your code, but you are going to want something like this:
In your css:
<style>
.highlight {
... whatever ...
}
</style>
And then, in your blade,
#if( $vehicule->adtype == 1 )
<span class="highlight"> ...... whatever ..... </span>
#endif
Or, if you want it inline,
<span class="{{ ($vehicule->adtype == 1) ? 'highlight' : '' }}">
I've just recently started using Laravel and I've got a problem, that my page is really slow.
The issue is that my queries are not ideal:
`
<div class="container">
#foreach ($product as $single)
<?php
$tagy = $single->tags()->get();
echo "<div class='item";
foreach($tagy as $tag) {
$premenna = Tags::where('id','=',$tag->tagID)->first();
echo " item".$premenna->id;
}
echo "'>";
?>
<div class="thumbnail porfolio">
<img class="image" src="<?=Croppa::url($single->destinationPath.'/'.$single->coverphoto, 250)?>" />
<div class="caption">
<div class="info">
<h4 style="font-weight: bold;">{{ $single->name }}</h5>
<p style="font-size: 15px; margin-bottom: 0px;">{{ $single->city }}</p>
<p class="date">{{ $single->date }}</p>
</div>
<div class="map-location">
<i class="fa fa-dot-circle-o fa-2x"></i>
</div>
<div class="tagy">
<?php
foreach($tagy as $tag) {
$variable= Tags::where('id','=',$tag->tagID)->orderBy('name')->first();
echo "<a class='hashtag tag".$variable->id."'>".$variable->name." </a>";
}
?>
</div>
</div>
</div>
</div>
#endforeach
</div>`
This is my Controller function:
protected function index()
{
$product = Product::where('active','=',1)->orderBy('date')->get();
$tagy = Tags::orderBy('name')->get();
return View::make('uvod',['product' => $product, 'tags' => $tagy]);
}
I've made one-to-many relationship between Product Class and ProductTag Class - that's the fucntion tags();
Could you please somehow help me optimizing the code (queries)? I would like to use #foreach function only once if possible - when i deleted the foreach functions inside the main one the page speed significantly improved.
Thank you very much for any kind of help :)
I am a bit of a newbie to both PHP and Laravel and I trying to build simple Web Apps in order to familiarize myself with both PHP and Laravel. I am getting an undefined variable in blade file. It would be appreciated if someone could help me clear this up.
Basically, what I want to happen is:
I have a View called dashboard.blade.php and in this view there is a text field and button. When the room number is entered and the button is clicked, the room number must get saved in the database and the current view needs to get refreshed but this time, the new room has to be shown at the top. The room gets saved in the database without a problem, but when I try to retrieve it using the foreach loop, I get the 'undefined variable rooms' error
I am using Laravel 5.2
The button concerned with firing off this action (in dashboard.blade.php)
<form action="{{ route('viewroom') }}" method="POST"> //route is viewroom
Please Insert The New Room Number<br>
<input type="text" name="roomid"/>
<button type="submit">Add New Room</button>
<input type="hidden" value="{{ Session::token() }}" name="_token"/>
</form>
Route file
Route::post('/dashboard',[
'uses' => 'RoomController#InsertRoom',
'as' => 'viewroom'
]);
Function used in the RoomController
public function InsertRoom(Request $request){
$this->validate($request, [
'roomid' => 'required | numeric | unique:insert_rooms',
]);
$room = new InsertRoom();
$room->roomid = $request['roomid'];
$room->status = 0;
$room->save();
$rooms = InsertRoom::all();
$request->session()->flash('alert-success', 'Room was successful added!');
return view('dashboard', ['rooms' => $rooms]);
}
In dashboard.blade.php:
<div class="border1">
#if(isset($results))
#foreach($rooms as $room)
$room->roomid
#endforeach
#endif
</div>
Any and all help would be appreciated. Thank you
UPDATE
I forgot to clarify that, I got the error 'undefined variable $rooms' BEFORE I used an if condition to check if $errors was set. After I used if(isset($errors)) I didnt get the error anymore but the information I wanted to show up didn't show up
UPDATE 2
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
<style>
h1{
text-align: center;
}
.border1{
border: dotted;
border-color: red;
text-align: center;
padding: 20px;
}
.ulerror{
text-align: center;
color: red;
}
.flash-message{
text-align: center;
font-weight: bolder;
color: lawngreen;
}
ul li{
font-family: "Lucida Console";
font-size: 24px;
list-style: none;
padding: 10px;
}
a{
padding: 8px;
}
</style>
</head>
<body>
<h1>Dashboard</h1>
<div class="border1">
#if(isset($rooms))
{{--{{ dd(isset($rooms)) }}--}}
#foreach($rooms as $room)
{{ $room->roomid }}
#endforeach
#endif
{{--1 IGNORE THIS--}}
</div>
<br><br><br>
<div class="border1">
<b>Insert a new Room</b>
<br><br>
<form action="{{ route('viewroom') }}" method="POST">
Please Insert The New Room Number<br>
<input type="text" name="roomid"/>
<button type="submit">Add New Room</button>
<input type="hidden" value="{{ Session::token() }}" name="_token"/>
</form>
</div>
<div class="flash-message">
#foreach (['danger', 'warning', 'success', 'info'] as $msg)
#if(Session::has('alert-' . $msg))
<p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }} ×</p>
#endif
#endforeach
</div> {{--flash message--}}
#if(count($errors) > 0)
<div class="ulerror">
<ul>
#foreach($errors->all() as $error)
{{ $error }}
#endforeach
</ul>
</div> {{--error handling--}}
#endif
You should try
<div class="border1">
#if(isset($rooms))
#foreach($rooms as $room)
{{$room->roomid}}
#endforeach
#endif
Typo Error: rooms instead of results. You haven't passed any variable named 'results' from your controller to view.
You just need to check if result object(rooms) is set or not. You can use any of below to do this.
All will return boolean result true or false.
#if($rooms)
#foreach($rooms as $room)
{{$room->roomid}}
#endforeach
#endif
OR
#if(!empty($rooms))
#foreach($rooms as $room)
{{$room->roomid}}
#endforeach
#endif
OR
#if(isset($rooms))
#foreach($rooms as $room)
{{$room->roomid}}
#endforeach
#endif
Instead of doing this:
return view('dashboard', ['rooms' => $rooms]);
Just print out all your rooms in your get view function. And then in your insertRooms function do a:
return redirect()->back();
Instead then your get view will automatically print out the new values because of a page refresh :-)
And please start using the compact method to return variables to your views, i has been best practice sine laravel 5.1 :-)
Also i would advice you to watch some videos on nameing conventions. Best of luck!