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
Related
I've made a blog and now I'm trying to implement a comment section. I want it so that when the user tries to post, it's saves the comment and redirects the user to the same page. But when I write a comment and try to post it, the application redirects me to a different page. I'm learning how to make a blog with laravel, so I don't know when to use url and when to use routes. Here's the code that I've written.
#auth
<div class="card ml-5 col-lg-8">
<ul class="list-group list-group-horizontal">
<h5 class="list-group-item active">
Comments
<h5>
<div class="card-body">
<form method="post" action="{{url('save-comment/'.Str::slug($blog->title).'/'.$blog->id)}}">
#csrf
<textarea name="comment" class="form-control py-5"></textarea>
<input type="submit" class="btn btn-primary mt-3">
</div>
</ul>
</div>
#endauth
<div class="card ml-5 col-lg-8">
<h5 class="card-header mb-4">Comments<span class="badge badge-info ml-2"> {{count($blog->comments)}}</span></h5>
<div class="card-body mt-3">
#if($blog->comments)
#foreach($blog->comments as $comment)
<blockquote class="blockquote">
<p class="mb-0">{{$comment->comment}}</p>
<footer class="blockquote-footer">Username</footer>
</blockquote>
<hr>
#endforeach
#endif
</div>
</div>
BlogController :
function save_comment(Request $request,$slug,$id)
{
$request->validate([
'comment'=>'required',
]);
$data = new Comment;
$data->user_id=$request->user()->id;
$data->post_id=$id;
$data->comment=$request->comment;
$data->save();
return back();
}
Routes :
Route::get('/blog/', [App\Http\Controllers\BlogController::class, 'index'])->name('blog');
Route::get('blogs/{slug}','App\Http\Controllers\BlogController#getArticles')->name('article.show');
Route::get('blog.update/{id}','App\Http\Controllers\BlogController#edit');
Route::put('blog.update/{id}','App\Http\Controllers\BlogController#update');
Route::post('save_comment/{slug}/{id}','App\Http\Controllers\BlogController#save_comment')->name('save_comment');
Route::get('/admin/blog', 'App\Http\Controllers\BlogController#getBlog')->name('admin.blog');
If there's someone willing to assist come up with a solution to this problem, please assist me. I think the problem lies where I've written the url lies. When I change the url to route, it gives me an error of route not defined.
Route::resource('/blog','App\Http\Controllers\BlogController');
It redirects you to an empty page because you made a mistake on the url of your route. In your web.php file, your route is :
Route::post('save_comment/{slug}/{id}', 'App\Http\Controllers\BlogController#save_comment')->name('save_comment');
While in your form you wrote save-comment/ :
<form method="post" action="{{url('save-comment/'.Str::slug($blog->title).'/'. $blog->id)}}">
The error is due to this. I therefore advise you to modify the action in your form like this save_comment/:
<form method="post" action="{{url('save_comment/'.Str::slug($blog->title).'/'. $blog->id)}}">
This should be fixed !
Please change your code like this and check...
action="{{route('save_comment', $blog->id])}}"
Route::post('save_comment/{id}','App\Http\Controllers\BlogController#save_comment')->name('save_comment');
**BlogController**
function save_comment($id, Request $request)
{
$request->validate([
'comment'=>'required',
]);
$data = new Comment;
$data->user_id=$request->user()->id;
$data->post_id=$id;
$data->comment=$request->comment;
$data->save();
return back();
}
I am quite new to Laravel
I have two views
Book
Read
The Book View displays a single book
<section class="cont-readingone">
<div class="container">
<div class="row row-grid">
<div class="col-md-6">
<div class="row">
<div class="col-md-6">
<div class="cont-reading-image">
<img src="{{ $book->image_url }}" alt="trending image" />
</div>
</div>
<div class="col-md-6">
<div class="out-box">
<h2>{{ $book->name }}</h2>
<h3>{{ $book->author->name }}</h3>
<br>
Start Reading<br><br>
<img src="\images\cart-buy.png" width="13px"/> Buy
</div>
</div>
</div>
</div>
In my controller, I was able to achieve it using
public function show(Book $book) {
$relatedBooks = Book::where('author_id', $book->author_id)
->where('id', '!=', $book->id)
->get();
return view('book')->with('book', $book)->with('relatedBooks', $relatedBooks);
}
In my web.php
Route::get('/books/{book}', [BooksController::class, 'show'])->name('book');
What I am trying to achieve is that, when I click Start Reading on
the Single Book Page, it takes me to another view page (Read) but it takes the book id that I clicked.
In the Read View I have this code,
<script>
"use strict";
document.onreadystatechange = function () {
if (document.readyState == "complete") {
window.reader = ePubReader("{{ $book->epub_url }}", {
restore: true
});
}
};
</script>
My problem is that I don't know how to take the id of the book that I
click and Pass it to the Read View
I will be glad if someone can explain the logic to me as I am confused.
To do via POST
//Book View
//change Start Reading to
<form action="{{ route("your.route.to.read") }}" method="POST">
#csrf
<input name="book_id " value ={{$book->id}} hidden>
<button type="submit">Start Reading</button>
</form>
//your Route will be
Route::get('/read',YourReadController#yourFunction)->name('your.route.to.read');
//your controller will be
public function yourFunction(Request $request)
{
//book id is in $$request->book_id
//your operation here
return view('read')->with('data',$dataYouWantToSend);
}
To do via GET
//Book View
//change Start Reading<br><br> to
Start Reading
//route for get will be
Route::get('/read/{book_id}',YourReadController#yourFunction)->name('your.route.to.read');
//your countroller will be
public function yourFunction($book_id)
{
//book id is in $book_id
//your operation here
return view('read')->with('data',$dataYouWantToSend);
}
I'm making a forum with themes and topics. If a user clicks on a theme, he/she gets to see all the topics within that theme. Here we encounter the first problem. In the theme.blade.php I have a title: <span class="card-title">{{ $theme->theme_title }} - Topics</span>. This title is supposed to show the title of the theme that the user clicked on. But it shows (just a wild guess) some random theme title from the database that is not even connected to this topic.
Now I made an extra view for the user. If the user clicks on a topic from the selected theme. He/she is supposed to redirect to the topic that he/she clicked on but instead its shows (again) some random topic from the database that is not connected to the topic/theme at all. Instead of the topic that the user clicked on. In this GIF http://imgur.com/a/vOQFT you can see the problem If u look at the profile picture and username. Maybe the problem is in the Web.phpor somewhere else, I don't know. Sorry for the long story but I couldn't figure out how say this in a better way. I think I switched some things up in the code.
Here is the every file of code where this problem may occur
Web.php
Route::get('/', 'ThemesController#index')->name('home');
Route::get('/theme/{theme_id}/topics', 'ThemesController#show')->name('showtheme');
Route::get('/theme/{theme_id}/topics/{topic_id}', 'TopicsController#show')->name('showtopic');
Route::group(['middleware' => 'App\Http\Middleware\AdminMiddleware'], function() {
//THEMES
Route::get('/theme/{theme_id}/edit', 'ThemesController#edit')->name('edittheme');
Route::patch('/theme/{theme_id}/edit', 'ThemesController#update')->name('updatetheme');
Route::get('/theme/create', 'ThemesController#create')->name('createtheme');
Route::post('/theme/create', 'ThemesController#save')->name('savetheme');
Route::delete('/theme/{theme_id}/delete', 'ThemesController#destroy')->name('deletetheme');
//TOPICS
Route::get('/theme/{theme_id}/topics/{topic_id}/edit', 'TopicsController#edit')->name('edittopic');
Route::patch('/theme/{theme_id}/topics/{topic_id}/edit', 'TopicsController#update')->name('updatetopic');
Route::get('/theme/{theme_id}/topics/create', 'TopicsController#create')->name('createtopic');
Route::post('/theme/{theme_id}/topics/create', 'TopicsController#save')->name('savetopic');
Route::delete('/theme/{theme_id}/topics/{topic_id}/delete', 'TopicsController#destroy')->name('deletetopic');
});
Route::get('user/profile', 'UserController#profile')->name('showprofile');
Route::post('user/profile', 'UserController#update_avatar');
Theme.blade.php (The list of every topic within the theme)
<div class="col s12">
<div class="card">
<div class="card-content"><span class="card-title">{{ $theme->theme_title }} - Topics</span>
<div class="collection">
#foreach($topics as $topic)
<a href="{{ route('showtopic', ['theme_id' => $theme->id, 'topic_id' => $topic->id ]) }}" class="collection-item avatar collection-link"><img src="/uploads/avatars/{{ $topic->user->avatar }}" alt="" class="circle">
<div class="row">
<div class="col s6">
<div class="row last-row">
<div class="col s12"><span class="card-title">{{ $topic->topic_title }}</span>
<p>{!! str_limit($topic->topic_text, $limit = 125, $end = '...') !!}</p>
</div>
</div>
<div class="row last-row">
<div class="col s12 post-timestamp">Posted by: {{ $topic->user->username }} op: {{ $topic->created_at }}</div>
</div>
</div>
<div class="col s2">
<h6 class="title center-align">Replies</h6>
<p class="center replies">{{ $topic->replies->count() }}</p>
</div>
<div class="col s2">
<h6 class="title center-align">Status</h6>
<div class="status-wrapper center-align"><span class="status-badge status-open">open</span></div>
</div>
<div class="col s2">
<h6 class="title center-align">Last reply</h6>
<p class="center-align"></p>
<p class="center-align">Tijd</p>
</div>
</div>
</a>
#endforeach
</div>
</div>
</div>
</div>
ThemesController.php (Only show method)
public function show($id)
{
$theme = Topic::find($id)->theme;
$topics = Theme::find($id)->topics;
return view('themes.theme')->with('topics', $topics)->with('theme', $theme);
}
TopicsController.php(Only show method)
public function show($id)
{
$theme = Theme::find($id);
$topic = Topic::find($id);
return view('topics.topic')->with('theme', $theme)->with('topic', $topic);
}
Thanks for looking at my code. This problem has been sitting here for quite a while and I want to move on. Thanks for your help!
Your controller code simply finds the theme with ID $id, and the topic (singular!) with ID $id. That particular topic may not appear in that particular theme at all. They likely have nothing to do with each other.
To find the topics belonging to the theme with ID $id, you would do this:
$theme = Theme::find($id)->with('topics');
(this assumes your model relationships are set up correctly, you have not show us those). See the docs on eager loading.
To access the topics in your view, do something like this:
#foreach ($theme->topics as $topic)
...
{{ $topic->user->username }}
...
While developing, you can simply
return $theme;
in your controller to see the structure of the data, so you can work out how to handle and iterate over it.
In my application, I have the concept of a user profile. The information that gets displayed differs depending on whether the user is viewing their own profile or another user's profile. Here's a simplified view of UsersController#show:
public function show($id)
{
$user = User::findOrFail($id);
$currentUser = Auth::user();
return view ('users.show', compact('user', 'currentUser'));
}
In my view, I end up having to write code that looks like:
#if ($currentUser === $user->id)
<section class="container search-form visible-nav">
<div class="row">
<div class="col-xs-12">
#include ('partials._search')
</div>
</div>
</section>
#endif
This seems like a clumsy implementation, especially for a language like Laravel. Is there a more concise way to achieve the same result in my views?
Not really. You need to check if current user is the viewed user somewhere - either in the controller or in the view.
You could simplify your code a bit though:
public function show($id)
{
$user = User::findOrFail($id);
return view ('users.show', compact('user'));
}
#if (Auth::id() === $user->id)
<section class="container search-form visible-nav">
<div class="row">
<div class="col-xs-12">
#include ('partials._search')
</div>
</div>
</section>
#endif
There are some other options like returning different blade templates depending on whether the current user is the same as the viewed user, but if the only difference would be a few #ifs I would keep it in one template.
In my application, I've always been able to pass data to any view as one would normally do using view('myView', compact('data'));. As of today, any view I try to render this way times out. I'm getting the error Maximum execution time of 120 seconds exceeded in Whoops!. I tried increasing php.ini and httpd.conf timeout times but no cigar. It's really odd and it doesn't make sense to me because I've always been able to render my views almost instantly, even when retrieving 15k+ records from the database and passing them to the view like I've always done.
My controller:
use App\Product;
use Illuminate\Support\Facades\Session;
class HomeController extends Controller {
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
//the controller is normally like this
//$products = Product::paginate(16);
//return view('home', compact('products'));
//I'm testing with these 2 lines below but no cigar.
$product = Product::wherePid(303)->first();
return view('test', compact('product'));
}
}
The test view I created:
#extends('app')
#section('content')
{{ $product->name }}
#stop
My application view:
#extends('app')
<pre>{{ var_dump(Session::all())}}</pre>
#section('content')
<div class="row">
#foreach($products as $product)
<div class="col-xs-6 col-sm-3 col-lg-3 col-md-3">
<?php
if($product->img[7] == 'm' || $product->img[7] == 'M') echo "<div class='continenteIcon'></div>";
else echo "<div class='jumboIcon'></div>";
?>
<div class="thumbnail">
<a href="products/{{$product->pid}}"><img src="{{$product->img}}" title="
<?php
if($product->dispname != '') echo $product->dispname;
else echo $product->name;
?> ">
</a>
<div class="caption">
<h4>
<a style="text-decoration:none;" class="wordwrap" title="
<?php
if($product->dispname != '')
echo $product->dispname;
else echo $product->name;
?>" href="products/{{$product->pid}}">
<?php
if($product->dispname != '')
echo $product->dispname;
else echo $product->name;?>
</a>
</h4>
<p>{{$product->brand}}</p>
<span class="pull-right price">€{{$product->price}}</span>
<br/>
<span class="pull-right ppk">€{{round($product->pricekilo, 2)}} Kg, L ou Und</span>
</div>
<div class="ratings">
<p class="pull-right"> {{-- # review--}}</p>
<p>
<form method="post" action="add/{{$product->pid}}">
<input type="hidden" name="_token" value="{{{ csrf_token() }}}" />
<button title="Adicionar ao carrinho" type="submit" class="btn btn-success">
<i class="fa fa-shopping-cart"></i>
</button>
</form>
<form method="post" action="products/related/{{$product->pid}}">
<input type="hidden" name="_token" value="{{{ csrf_token() }}}" />
<button title="Ver artigos semelhantes" style="position:relative; bottom:35px;" type="submit" class="btn btn-info pull-right">
<i class="fa fa-search"></i>
</button>
</form>
</p>
</div>
</div>
</div>
#endforeach
</div>
<div class="row">
{!! $products->render() !!}
</div>
<div class="row">
<div class="pull-right">
* Preço por unidade, Litro ou Kilograma
</div>
#stop
#section('scripts')
#stop
The problem doesn't only happen in this view, but every single time I try to fecth someting from the database and pass it to the view to render. I keep getting timeouts and I can't seem to fix it no matter what I do.
I am clueless why this is happening. It seems like it started out of the blue. I have no Idea what could be causing this issue.
Any help?
P.S.: I'm using Wamp.
EDIT: I forgot to add something that might be important:
Everything is up and running in Wamp. If I dd() out the query result and do not render the view
$products = Product::paginate(16);
dd($products);
//return view('home', compact('products'));
this is fast, as it always used to be. And by fast I mean it takes less than 1 second to retrieve everything I need. But if I render the view with
return view('home', compact('products'));
everything just stalls and I get a 500 (I checked with Fiddler2 and after the page stops loading, the request status is 500)
It seems like you may be requesting too many records which may be using too much of your RAM. I would use the chunk command to help you with managing the amount you're requesting.
For example:
User::chunk(200, function($users)
{
foreach ($users as $user)
{
//
}
});
First check logs.
Next try to dd($product)
Next if you try to render view with last 2 lines (getting first record) remove pagination from template.
Clean template to minimum e.g.
#extends('app')
#section('content')
<div class="row">
#foreach($products as $product)
#endforeach
</div>
#stop
I just sorted it out. The issue was in the following block of code in app.blade.php.
$size = Session::get('size');
...
<input type="text" value="'.Session::get($item).'">
...
I was messing around with data from an existing session and everything was working fine. I assumed I was doing it right. I wasn't. Not by a chance :)
Assumption is the mother of all screw ups.
Surrounded the whole block with if(Session::has('size') and everything is blazing fast and running smoothly as usual.
Thanks #Pyton for pointing me out into the right direction and thanks everyone for your contribution.