Laravel No query results for model [App\Topic] create - php

I'm trying to get a view where the user is able to create a topic. I did this many times in my project but never got this error, Because all of the other ones work just fine.
I get the error No query results for model [App\Topic] create. Here is the code.
This is the link that is supposed to bring the user to the view.
<div class="col s12">
<div class="card">
<div class="card-content clearfix">
New topic <i class="material-icons right">edit</i>
</div>
</div>
</div>
These are the routes that are used in this problem.
Route::get('/theme/{theme_id}/topics/create', 'TopicsController#create')->name('createtopic');
Route::post('/theme/{theme_id}/topics/create', 'TopicsController#store')->name('savetopic');
The Controller method create.
dd('Hij is er ' . $id);
And the store method is empty, The link doesn't show the DumpDie method but shows me the error instead. So there is no need to post the view i'm trying to display because that's not where the problem is. Thanks in advance!

You need to understand how routes and controller methods are working
Route::get('/theme/{theme_id}/topics/create', 'TopicsController#create')->name('createtopic');
When you are hitting the above route, i mean something for example yourdomain/theme/1/topics/create in your browser, then it will take 1 in place of theme_id and it will go to the create method of your TopicsController which will accept one argument.
Your create method should be something like that
public function create($id)
{
dd($id);
}
Here you will get 1 as result, because you have passed this argument in your url instead of theme_id.

Related

Passing data from the database to a blade view using a controller in laravel

I found several ways to do what I need to do, the first way was using the rounting using the web.php file. But according to serveral posts this creates vulnerabilities in the application. So I found out the correct usage is with a controller that manages the database queries.
I created a controller, named EventsController and put this into it:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class EventsController extends Controller
{
public function index()
{
$events = DB::table('eventaries')->select('id','coursname','start', 'end', 'category')->get();
return view('components.course-list')->with('eventaries', $events);
}
}
the blade is inside the folder: /resources/views/components/course-list.blade.php
Inside the blade I use this code:
<div class="px-6 py-20">
<div class="max-w-7xl mx-auto">
<!-- Course List -->
{{ $events->coursname}}
</div>
</div>
But I get the error:
Undefined variable $events (View: D:\laragon\www\censored\resources\views\components\course-list.blade.php)
When using the with method on a view the first argument (key) becomes the name of the variable in the view and the second argument (value) becomes it's value.
This means you need to use $eventaries in your view instead of $events or rename the key in your controller return view('components.course-list')->with('events', $events);.
Also, I'm not sure about defining the action directly in the routes file causes vulnerabilities. I just think that the routes file, which is often the first entry point for developers when exploring a Laravel app, becomes hard to read/manage.
->with('eventaries', $events) means that you are passing the value of $events as eventaries. So in the blade you need to access it using $eventaries instead. So now blade code would be:
<div class="px-6 py-20">
<div class="max-w-7xl mx-auto">
<!-- Course List -->
{{ $eventaries->coursname}}
</div>
</div>
You have given 'eventaries' as the name for events. So you can only access it with $eventaries within the view, not as events.
you are passing to the view the value using the "with" method, and it does it like a value/key pair (->with($key, $value)). In your case you declare it like
return view('components.course-list')->with('eventaries', $events);
so, in the view you can access the value through the $eventaries, not the $events. Also, the query result is a collection and you will need to loop it to get each item
<div class="px-6 py-20">
<div class="max-w-7xl mx-auto">
<!-- Course List -->
#foreach($eventaries as $event)
{{ $event->coursename }}
#endforeach
</div>
</div>
What caused the issue?
The issue of this question was created because the router was never accessing the controller I created. I added the following code to my router to access the controller:
Route::get('/kursangebote/{course}', ['App\Http\Controllers\EventaryController', 'index'])->name('course.list-list');
In there I added the logic I wanted.
['App\Http\Controllers\EventaryController', 'index']
App\Http\Controllers\EventaryController is the controller I use, and index the function inside the controller I need to call. It might be a better Idea to use Eloquent for this https://laravel.com/docs/8.x/eloquent

Laravel: Check in controller if field has value before passing onto `view`

I have two table, one is User that stores login credentials and other is Userinfo that deals with storing personal information about the users. When a user sign up, they do not require filling up all the inputs for UserInfo table (i.e. they might only fill up the Gender and Religion fields out of a few other). So, the end result is that the UserInfo ends up being filled with only a couple of values or none at all.
The issue I am facing right now is when I pass through the data from both tables to view, and display them in typical laravel way, it throws an error Trying to get property of non-object. This is expected since not all the users have complete data from UserInfo table. I tried many methods both in controller and view to deal with the error message but failed to find a solution.
Is there a way to check the columns for empty or half complete value and deal with them properly in controller before passing onto the view? I think these checks should be performed in the controller or anywhere other than in the view. If there are none, how do I deal with them in the view? Maybe inside the loop? Solution and suggestions are greatly appreciated! Here's my code in the view:
#forelse($donors as $donor)
<div class="panel panel-default">
<div class="panel-heading"><i class="fa fa-list-alt"></i> {{$donor->name}}</div>
<div class="panel-body">
<div class="row">
<div class="col-md-6">
<div class="basic-info">
<h4>Basic Information</h4>
<p><strong>Blood Group: </strong>{{ $donor->user_info->blood }}</p>
<p><strong>Sex: </strong>{{ $donor->user_info->sex }}</p>
<p><strong>Religion: </strong>{{ $donor->user_info->religion }}</p>
<p><strong>Age: </strong>{{ \Carbon\Carbon::parse($donor->user_info->dob)->age }}</p>
</div>
</div>
</div>
</div>
</div>
#empty
<p>No records found!</p>
#endforelse
As you can see, because not all the user have complete data in the table, laravel throws the Trying to get property of non-object error. My controller has standard laravel method of passing data to views:
public function index(User $user, Request $request)
{
$donors = $user->with('user_info')->latest()->paginate(5);
return view('donors.index', compact('donors'));
}
Since version 5.5, Laravel has an optional() helper that I think it can help you.
Try something like this in your view:
optional($donor->user_info)->blood

Laravel Passing Multiple Variables to View

Learning through some videos for Laravel but hit an issue i cant seem to figure out.
I have a route
Route::get('/post/{id}/{name}/{password}', 'PostController#showPost');
A custom controller called PostController.php
public function showPost($id, $name, $password) {
return view('post', compact('id','name','password'));
}
and the view called post.blade.php
<div class="container">
<h1>Post {{$id}} {{$name}} {{$password}}</h1>
</div>
when running the url
http://127.0.0.1/post/1/2/3
I get back a 404 page.
Looks like you need to allow .htaccess files. The problem is your routes aren't working.
https://help.ubuntu.com/community/EnablingUseOfApacheHtaccessFiles

How to route, fetch and display data from two tables in db to a single webpage in laravel 5.2

im new to laravel and i am currently doing a study project in laravel 5.2. Thr project is just a simple website having 3 pages (Home, About Us, Contact Us) fetching each page content from database and the home page having a slideshow. For that i downloaded a free responsive html template and divided it into header.blade.php, slideshow.blade.php,footer.blade.php and stored it inside a folder named includes under view folder. And the main layout file default.blade.php is stored inside a folder named layouts under view folder. I included these header.blade.php, slideshow.blade.php and footer.blade.php in the main layout file default.blade.php to form the full web template.
My default.blade.php file code is as given below:
<!DOCTYPE html>
<head>
#include('guest.includes.head')
</head>
<body>
<div class="wrap-body">
<header>
#include('guest.includes.header')
</header>
#if(Request::is('/'))
#include('guest.includes.slideshow')
#endif
#yield('content')
<footer class="zerogrid">
#include('guest.includes.footer')
</footer>
</div>
</body>
</html>
Inside the header.blade.php i had some information like phone num, email, website address that are fetched from database and displaying that data on all my 3 pages along with each page contents from db. For that i used share() function inside boot method of AppServiceProvider.php to share and display my header data on all my webpages.
and my current slideshow.blade.php code is like as given below:
<div class="zerogrid">
<div class="callbacks_container">
<ul class="rslides" id="slider4">
<li>
<img src="assets/images/banner1.jpg" alt="">
<div class="caption">
<h2>Title 1</h2></br>
<p>Description 1</p>
</div>
</li>
<li>
<img src="assets/images/banner2.jpg" alt="">
<div class="caption">
<h2>Title 2</h2></br>
<p>Description 2</p>
</div>
</li>
</ul>
</div>
</div>
Here you can see that i had hard-coded the slideshows slide item details(slideimage, title, description) above. Upto this part is working fine and i am getting header data from db to server via header.blade.php to all pages, each page contents from db via Routes/Controllers and the above said slideshow.
My routes.php code is as given below:
Route::get('/', 'GuestController#home');
Route::get('aboutus', 'GuestController#aboutus');
Route::get('contactus', 'GuestController#contactus');
My Controller Page(GuestController.php) code is as given below:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
class GuestController extends Controller
{
public function home() {
$result=DB::table('contents')->where('menuname','home')->get();
return view('guest.home')->with('data',$result);
}
public function aboutus() {
$result=DB::table('contents')->where('menuname','aboutus')->get();
return view('guest.aboutus')->with('data',$result);
}
public function contactus() {
$result=DB::table('contents')->where('menuname','contactus')->get();
return view('guest.contactus')->with('data',$result);
}
}
Now i want to make the slideshow also to be dynamic. I mean to fetch the slide item details (slideimage, title, description) also from db itself. For that i created a table named slideshow with fields slideimage, title, description. But i dont know how to fetch and display data from two independant tables (slideshow & contents) in db to a single web page.
(Here in my case actually in my home page it will fetch 3 sets of data from db. first set of data is header data from headers table that will display header data like phone, email, website etc to all my pages including homepage via share() function and the second set of data is the home page contents from content table via routes/controller pages. These two are already working and now iwant to fetch data for slideshow also from slideshow table in db which is my 3rd set of data to be display on homepage.)
Any solution for this requirement? Please Help! Thanks in advance...
When i searched for various solutions for my requirement as asked in my above question, i found a simple method of satisfying this requirement of fetching and displaying datas from two tables inside a single view can be done by just modifying the home() method in the above given controller page code ( GuestController.php ) as given below:
public function home() {
$homecontent=DB::table('contents')->where('menuname','home')->get();
$slideshow=DB::table('slideshow')->get();
return view('guest.home')->with('homecontent',$homecontent)->with('slideshow',$slideshow);
}
Then inside the slideshow.blade.php loop the result from slideshow variable like:
<ul class="rslides" id="slider4">
#foreach($slideshow as $row)
<li>
<img src="assets/images/{{$row->slideimage}}" alt="">
<div class="caption">
<h2>{{$row->title}}</h2></br>
<p>{{$row->description}}</p>
</div>
</li>
#endforeach
</ul>
and same like slideshow, loop the contents of the homecontent variable inside the homepage file something like:
#foreach($homecontent as $row)
<article>
<div class="art-header">
<h3>{{$row->contenttitle}}</h3>
</div>
<div class="art-content">
<img src="assets/images/{{$row->contentimage}}" />
<p align="justify">{{$row->contentdescription}}</p>
</div>
</article>
#endforeach
No other changes required in any other pages and it will display slideshow and homepage contents inside the homepage itself along with the shared header datas from header table on all pages including homepage.
You have answered your own question and you should probably select it as a answer for this thread.
(Comments are too short, that's why I am writing you an answer)
Since you said you are teaching yourself Laravel I would strongly recommend you watch this course. It is a free one and it seems to help people a lot. It certainly helped me too although I had previous experience with the framework.
Anyway you know how you write a project and then you come one year later and think "What the .. was I thinking when I wrote this?" So I believe we should name our things clearly and precisely just for the sake of saving our future selves' souls.
I hope you take this as a positive critique and not as bashing on you. With all respect to you I am just trying to convey some wisdom here...
What do I mean exactly:
1) you named your controller GuestController. But you have no guests table. Probably you don't have a users table too. So where are the guests? Your controller should be much rather named something along the lines of HomeController or FrontController or even split into may different controllers.
"NewsController"
The basic rule is "one table - one model - one controller" so first of all you should probably not keep your articles in the same table as your pages contents. What an experienced developer would do is have two separate tables for those. So probably NewsController for the news, a News model and a news table. Then another controller for the pages table, a Page model and a PagesController.
2)
"PagesController"
Here you can put your home and about pages.
so
class PagesController {
public function home(){ } //will show your slideshow and news feed
public function about() { } //will show the 'about' content from `contents`/`articles` table
}
then another one
class NewsController(){
public function show($id) { } //will show a single `news` article
}
depending on your site architecture you can
- have the slides editable trough the front part of the site or have an /admin/ directory with another set of controllers where you have another SlideController and a NewsController where you can add and edit news and slides
- or add controllers to the front part of the site to add/edit news and slides
Hope it helps along your way!
Regards
I recommend using Eloquent ORM
The model is made so
namespace App;
use Illuminate\Database\Eloquent\Model;
class Slideshow extends Model
{
protected $table='slideshow';
}
Then the controller so writing
namespace App\Http\Controllers;
use App\Slideshow;
use App\Contents;
public function __construct(Contents $contents)
{
$contents=$contents->get();
view()->share('data', $contents);
}
class GuestController extends Controller
{
public function home() {
$slideshows=Slideshow::where('menuname','home')->get();
return view('guest.home', [ 'slideshows'=>$slideshows]);
}
public function aboutus() {
return view('guest.aboutus', []);
}
public function contactus() {
return view('guest.contactus', []);
}
P.S. Do not forget to register contents model

Dynamic page creation not working in laravel

I'm trying to create a page dynamically for each courses that I'm adding in a database.
I have a CoursesController who is taking care of adding, displaying the courses.
So, when I click on a course, it should dynamically create a page for that course and show details in that course page.
In the route.php page, I have
Route::get('courses/{code}', [ 'as'=>'course-show', 'uses'=>'CoursesController#getShow']);
and in the
CoursesController.php
public function getShow($code){
return $code;
}
And in the index.blade.php for CoursesController,
<h4>{{ $course->name }}</h4>
Now, It create the link with a unique code (saved in database) and upon clicking there, it takes me to the course page with an error:
BadMethodCallException
Method [show] does not exist.
What might be the problem? Can anyone help me?
The getShow() function in your controller should be show().
Also URL::action() goes to a controller action.
You probably want URL::route()
<h4> {{ $course->name }} </h4>
or you could do this
<h4> {{ $course->name }} </h4>

Categories