Undefined Variable in Laravel 8 view - laravel

I just want to Pass a Variable to the views about page.
This is the controller file
public function about(){
$name ="maneth";
return view::make('about')->with('name', $name);
}
This is the about page
#switch($name)
#case(1)
#break
#case(2)
#break
#default
#endswitch
This is the web file
Route::get('/about',function(){
return view('about',[PagesController::class, 'about']);
});
The Error is $name is undefined
I'm Using Laravel Framework 8.75.0
and PHP 7.3.33

You are using callback in router's file and there you not sent the name variable,
You can bind controller and router file using :
Route::get('/about', [AboutController::class, 'about']);

Your controller action is never being executed as your route definition is returning a view directly.
Change your route so that it calls your controller and action.
Route::get('/about', [AboutController::class, 'about']);

As long as it doesn't require any real logic (database query etc.) you can do it with a closures in your route. Otherwise you have to call the controller from your route. This would look like this:
Route::get('/about', [AboutController::class, 'about' ])->name('about');
And this would be thee closures style:
Route::get('/about',function(){
$name = 'Slim Shaddy';
return view('about', ['name' => $name]);
});

Related

Laravel-5.8: route show don't return any values

In previous versions of Laravel I was using something like this in controller in show function
Route::resource( 'our-project', 'ProjectController' );
public function show( Project $project ) {
return view( 'portalComponents.projects.projectDetails', compact( 'project' ) );
}
I was trying the same in laravel 5.8 but the $project attributes comes empty.
Route model binding won't work for our-project/1 because laravel can't infer the model. It tries to bind the our-project placeholder to a variable that has the name name in the show method. That argument doesn't exist. Because if this the $project variable stays empty.
the following resource would work:
Route::resource( 'projects', 'ProjectController' );
because this uses the project placeholder in routes. Check the output from php artisan route:list
It is also possible to have the same resource with different prefixes:
Route::resource('projects', 'ProjectController');
Route::group(['prefix' => 'admin'], function () {
Route::resource('projects', 'ProjectController');
});
the first one is /projects/1 and the second one is /admin/projects/
For the sake of completness and as alternative to #MaartenDev right answer, if you want to define the name of the parameter used with a resource route you can use the parameters() function, i.e.:
Route::resource( 'our-project', 'ProjectController' )
->parameters(['our-project' => 'project']);

Laravel 5.8 error trying to get the 'id' property of non-object

I'm developing an application with Laravel 5.8. In my application, I have a controller that handles backend articles, and it works. I want to display my user-side information in such a way that a user can click on a link and see the detail of an article. For that, I have created a new controller a with a new namespace for the function show my redirection of navigation in different page does not focus that it is en route or URL with Laravel 5.8. Below is the function.
namespace App\Http\Controllers\Cybernaut;
use App\History;
use App\Http\Controllers\Controller;
class HistoryController extends Controller
{
public function show($id)
{
$history = History::find($id);
return view('show_history', compact('history'));
}
}
At the level of the home page I wanted to have my links like these:
<li><a data-hover="history" href="{{route('history.show',$history→id)}}"><span>history</span></a></li>
Error
ErrorException (E_ERROR) Property [id] does not exist on this
collection instance. (View:
C:\laragon\www\venome\resources\views\layouts\partial\header.blade.php)
And here is the route used for the show function.
Route::group(['namespace'=>'cybernaut'], function (){
Route::get('/history/{slug}','HistoryController#show')->name('history.show');
});
Try after modifying the thing I have these at the route level now.
Route::get('/', 'FrontController#index')->name('index');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/admin/dashboard', 'DashboardController#index')->name('admin.dashboard');
Route::group([], function () {
Route::get('/history', 'HistoryController#index')->name('history.index');
Route::get('/history', 'HistoryController#create')->name('history.create');
Route::get('/history/edit', 'HistoryController#update')->name('history.update');
Route::get('/history', 'HistoryController#destroy')->name('history.destroy');
});
Route::group(['namespace' => 'cybernaut'], function () {
Route::get('/history/{history}', [
'as' => 'show',
'uses' => 'HistoryController#show'
]);
});
At the level of the homepage I wanted to put my link like those here now;
#foreach($history as $history)
<li><a data-hover="history" href="{{url('/history/'.$history->id)}}"><span>history</span></a></li>
#endforeach
I have this error now:
Trying to get property 'id' of non-object (View:
C:\laragon\www\venome\resources\views\layouts\partial\header.blade.php)
I want an internaut to be able to navigate between the pages.
You have a conflict of variables on your homepage.
#foreach($history as $history)
should be
#foreach($histories as $history)
where $histories is filled in in your FrontController.
$histories = History::all();
When actually getting your single history object, I agree with Sapnesh's answer that you best doublecheck whether or not the object actually exists.
The error occurs because find() returns NULL when a model is not found.
find($id) takes an id and returns a single model. If no matching model
exist, it returns null.
findOrFail($id) takes an id and returns a single model. If no matching
model exists, it throws an error.
In your show() method,
Change:
$history = History::find($id);
To:
$history = History::findOrFail($id);

Laravel 5.6 Function () does not exist in route/web.php

This is my code using to send an email
Route::post('/mail/send', [
'EmailController#send',
]);
in EmailController this is the send action
public function send(Request $request)
{
$data = $request->all();
$data['email'] = Input::get('email');
$data['name'] = Input::get('name');
$obj = new \stdClass();
$obj->attr = 'Hello';
Mail::to("dev#mail.com")->send(new WelcomeEmail($obj));
}
getting a error as Function () does not exist
In your route/web.php file
Change it to
Route::post('/mail/send', 'EmailController#send');
Refer to the documentation to see the possible options to define routes:
https://laravel.com/docs/5.6/routing
Route's action method can be defined using a array, but not simply wrap controller#action in an array, you should assign it to array's key 'uses'.
In your example, it should be like this:
Route::post('/mail/send', [
'uses' => 'EmailController#send',
//'middleware' => .... assign a middleware to this route, if needed
]);
the array form usually is used when we want to specify more specification about the route like use a specific middleware and pass middleware parameters.
if you just want to define route's processing method you can simply use controller#action as Route::post's second parameter:
Route::post('/mail/send','EmailController#send');
In your route ...
Route::post('/mail/send','EmailController#send')->name('send_email');
Inside of your HTML form add below code...
<form action="{{route('send_email')}}" method="post">
...
{{csrf_field()}}

Laravel undefine variable in view

I'm new to laravel. Using version 5.4 and tried to search but don't see what I'm doing wrong. I keep getting an "Undefined variable: post" in my view. I'm also doing form model binding. Model binding works properly when manually entering URL. Just can't click on link to bring up edit view.
My routes:
Route::get('test/{id}/edit','TestController#edit');
My controller:
public function edit($id)
{
$post = Post::find($id);
if(!$post)
abort(404);
return view('test/edit')->with('test', $post);
}
My form:
{{ Form::model($post, array('route' => array('test.update', $post->id), 'files' => true, 'method' => 'PUT')) }}
You're assigning the post value to 'test', so should be accessible with $test rather than $post.
You probably want to do either of these two things instead:
return view('test/edit')->with('post', $post);
or
return view('test/edit', ['post' => $post]);
https://laravel.com/docs/5.4/views
Your controller is sending a variable named "test", but your error says that your blade file doesn't have the $post variable passed into it. This can be fixed by changing "test" to "post" in your controller.

Multiple routes to same Laravel resource controller action

I like to use resource controllers in Laravel, as it makes me think when it comes to data modelling. Up to now I’ve got by, but I’m now working on a website that has a public front-end and a protected back-end (administration area).
I’ve created a route group which adds an “admin” prefix, like so:
Route::group(array('before' => 'auth', 'prefix' => 'admin'), function()
{
Route::resource('article', 'ArticleController');
Route::resource('event', 'EventController');
Route::resource('user', 'UserController');
});
And I can access the methods using the default URL structure, i.e. http://example.com/admin/article/1/edit.
However, I wish to use a different URL structure on the front-end, that doesn’t fit into what resource controllers expect.
For example, to access an article, I’d like to use a URL like: http://example.com/news/2014/06/17/some-article-slug. If this article has an ID of 1, it should (under the hood) go to /article/1/show.
How can I achieve this in Laravel? In there some sort of pre-processing I can do on routes to match dates and slugs to an article ID, and then pass that as a parameter to my resource controller’s show() method?
Re-visiting this, I solved it by using route–model binding and a pattern:
$year = '[12][0-9]{3}';
$month = '0[1-9]|1[012]';
$day = '0[1-9]|[12][0-9]|3[01]';
$slug = '[a-z0-9\-]+';
// Pattern to match date and slug, including spaces
$date_slug = sprintf('(%04d)\/(%02d)\/(%02d)\/(%s)', $year, $month, $day, $slug);
Route::pattern('article_slug', $date_slug);
// Perform the route–model binding
Route::bind('article_slug', function ($slug) {
return Article::findByDateAndSlug($date_slug);
});
// The actual route
Route::get('news/{article_slug}', 'ArticleController#show');
This then injects an Article model instance into my controller action as desired.
One simple solution would be to create one more route for your requirement and do the processing there to link it to the main route. So, for example:
//routes.php
Route::get('/arical/{date}/indentifier/{slug}', array (
'uses' => 'ArticleController#findArticle'
));
//ArticleContoller
public function findArticle($date,$slug){
$article = Article::where('slug','=','something')->first(); //maybe some more processing;
$article_id = $article->id;
/*
Redirect to a new route or load the view accordingly
*/
}
Hope this is useful.
It seems like if Laravel 4 supports (:all) in routing, you would be able to do it with ease, but unfortunately (:all) is not supported in Laravel 4.
However, Laravel 4 allows detecting routes by regular expression, so we can use ->where('slug', '.*').
routes.php: (bottom of the file)
Route::get('{slug}', 'ArticleController#showBySlug')->where('slug', '.*');
Since Laravel will try to match the top most route in routes.php first, we can safely put our wildcard route at the bottom of routes.php so that it is checked only after all other criteria are already evaluated.
ArticleController.php:
class ArticleController extends BaseController
{
public function showBySlug($slug)
{
// Slug lookup. I'm assuming the slug is an attribute in the model.
$article_id = Article::where('slug', '=', $slug)->pluck('id');
// This is the last route, throw standard 404 if slug is not found.
if (!$article_id) {
App::abort(404);
}
// Call the controller's show() method with the found id.
return $this->show($article_id);
}
public function show($id)
{
// Your resource controller's show() code goes here.
}
}
The code above assumes that you store the whole URI as the slug. Of course, you can always tailor showBySlug() to support a more advanced slug checking.
Extra:
You could also do:
Route::get('{category}/{year}/{slug}', 'ArticleController#showBySlug')->where('slug', '.*');
And your showBySlug() would just have additional parameters:
public function showBySlug($category, $year, $slug)
{
// code
}
Obviously you can extend to month and day, or other adaptations.

Resources