I'm trying to pass anINT from this URL: myapp.build/courses/anINT (implemented in the CoursesController) to $id in the Lesson_unitsController function below. I've tried a lot of solutions, but I can't seem to get it right.
The function in the CoursesController which implements the url is:
public function show($id)
{
$course = Course::find($id);
return view('courses.show')->with('course', $course);
}
Part of the show.blade.php file is:
#if(!Auth::guest())
#if(Auth::user()->id == $course->user_id)
Edit Course
Lesson Units
{!!Form::open(['action'=> ['CoursesController#destroy', $course->id], 'method' => 'POST', 'class' => 'float-right'])!!}
{{Form::hidden('_method', 'DELETE')}}
{{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
{!!Form::close()!!}
#endif
#endif
The Lesson_unitsController functions are:
public function index()
{
$lesson_units = Lesson_unit::orderBy('title','asc')->paginate(10);
return view('lesson_units.index')->with('lesson_units', $lesson_units);
}
public function specificindex($id)
{
$course = Course::find($id);
return view('lesson_units.specificindex')->with('lesson_units', $course->lesson_units);
}
And the specificindex.blade.php file is:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Dashboard</div>
<div class="card-body">
Create lesson unit
<p>
<h3>Your lesson_units</h3>
#if(count($lesson_units) > 0)
<table class="table table-striped">
<tr><th>Title</th><th></th><th></th></tr>
#foreach($lesson_units as $lesson_unit)
<tr><td>{{$lesson_unit->title}}</td>
<td>Edit</td>
<td>
{!!Form::open(['action'=> ['Lesson_unitsController#destroy', $lesson_unit->id], 'method' => 'POST', 'class' => 'float-right'])!!}
{{Form::hidden('_method', 'DELETE')}}
{{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
{!!Form::close()!!}
</td>
</tr>
#endforeach
</table>
#else
<p>You have no lesson unit.</p>
#endif
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
You are logged in!
</div> </div> </div> </div> </div>
#endsection
The routes in web.php are:
Route::resource('courses', 'CoursesController');
Route::resource('lesson_units', 'Lesson_unitsController');
Route::get('/courses/{id}', 'Lesson_unitsController#specificIndex');
I want that when the link for Lesson Units is clicked on the page, the id in the url is passed to the specificindex function in the Lesson_unitsController. Now, I get just a blank page. What am I doing wrong?
Try to understand the concept of RESTful and CRUD.
By using Route::resource('courses', 'CoursesController');, Laravel has helped you to register the following routes:
Route::get('courses', 'CoursesController#index');
Route::get('courses/create', 'CoursesController#create');
Route::post('courses/{course}', 'CoursesController#store');
Route::get('courses/{course}/edit', 'CoursesController#edit');
Route::put('courses/{course}', 'CoursesController#update');
Route::delete('courses/{course}', 'CoursesController#destroy');
Then, when you make GET request to myapp.build/courses/123, Laravel will pass the request to the show function of your CoursesController like:
public function show(Course $course)
{
return view('lesson_units.index')->with('lesson_units', $course->lesson_units);
}
Laravel will automatically resolve the Course from your database using the parameter passed into the route myapp.build/courses/{course}.
Note: The variable name $course has to match with the one specify in route /{course}.
You don't have a route set up to handle the $id coming in. The resource method within the Route class will provide a GET route into your Lesson_unitsController controller without an expectation of any variable. It is the default index route, and by default doesn't pass a variable.
There are a couple of ways to do this, but the easiest is to just create a new route for your specific need:
Route::get('lesson_units/{id}', 'Lesson_unitsController#specificIndex');
And then make your specificIndex function in your controller with an incoming variable:
public function specialIndex($id)
{
$course = Course::find($id);
// return view to whatever you like
}
HTH
Related
I'm working with Laravel 5.1
I have a template for a page that was previously working fine. I could hit my route and the page would be rendered as expected. At some point the page started just displaying the text contained in the blade template rather than rendering my page. To my knowledge nothing had changed in my routes file, controller or blade. Is there anything that is known to cause this to happen? I've tried updating permissions, using a different method to call the view and creating a new view file all together.
The route:
Route::group(['prefix' => '/admin'], function() {
Route::group(['prefix' => '/reactor-rules'], function() {
Route::get('/visual-rules/{track_id?}', [
'as' => 'broker_visual_reactor_rules',
'uses' => 'ReactorRulesController#visualRules'
]);
});
});
ReactorRulesController#visualRules:
public function visualRules(IReactorTrackDAO $reactorTrackDAO, $id = 0)
{
$export = new ReactorExport();
$tracks = $export->getReactorTracks();
if ($id == 0) {
$eventsArray = [];
}
else {
$eventsArray = $export->getArrayForTrack($id);
}
return $this->renderView('enterpriseBroker::reactor-rules.visual-rules', compact('eventsArray','tracks','reactorTrackDAO'));
}
My blade:
#extends($layout)
{{ SEO::setPageTitle(trans('enterpriseBroker::reactorRules.title'), false) }}
#section('content')
<br>
<br>
#if(empty($eventsArray))
<p>Please select a track below to view/export rules.</p>
#foreach($tracks as $track)
{{$track->name}}<br>
#endforeach
#else
#foreach($eventsArray as $track => $events)
<h4>{{$track}}</h4>
<a href="{{url().'/admin/visual-rules/'.$reactorTrackDAO->findByName($track)->id.'/download'}}" class="btn btn-primary" download>Export</a><br>
#foreach($events as $id => $event)
#if (count($event['rules']) > 0)
<div id="{{$track.'-'.str_replace(' ','_',$event['name'])}}">
<div class="col-lg-12">
<hr/>
<div class="col-lg-2">
<h4>{{$event['name']}}</h4>
</div>
<div class="col-lg-10 border border-primary">
#foreach($event['rules'] as $ruleId => $rule)
<h5>{{$rule['name']}}</h5>
<div class="col-lg-6">
<h6>Conditions to be met:</h6>
#foreach($rule['conditions'] as $condition)
<p>{{$condition}}</p>
#endforeach
</div>
<div class="col-lg-6">
<h6>Actions to run:</h6>
#foreach($rule['actions'] as $action)
<p>{!!$action!!}</p>
#endforeach
</div>
#endforeach
</div>
</div>
</div>
#endif
#endforeach
#endforeach
#endif
#endsection
#section('scripts')
#endsection
This is how it originally appeared:
This is how it currently appears:
It seems to be error with $layout
Try to test it using a hard coded value as below:
#extends('layouts.app')
and run below command
php artisan view:clear
I resolved the issue by creating a new blade file, pasting the contents of the old one in and pointing my controller to the new view. I'm not sure how this resolved the issue.
I have two tables, Companies and Projects. A company hasMany projects and a project belongsTo a company.
Company.php model
protected $fillable = [
'id', 'name', 'description'
];
public function projects()
{
return $this->hasMany('App/Project');
}
Project.php model
protected $fillable = [
'name', 'description', 'company_id', 'days'
];
public function company()
{
return $this->belongsTo('App/Company');
}
From my index.blade.php, I list the companies only and I have made them clickable so that when a user clicks on a company listed, they are taken to show.blade.php where the name of the company and the projects that belong to that company are displayed like so.
<div class="jumbotron">
<h1>{{ $company->name }}</h1>
<p class="lead">{{ $company->description }}</p>
</div>
<div class="row">
#foreach($company->projects as $project)
<div class="col-lg-4">
<h2>{{ $project->name }}</h2>
<p class="text-danger">{{ $project->description }}</p>
<p><a class="btn btn-primary" href="/projects/{{ $project->id }}" role="button">View Projects »</a></p>
</div>
#endforeach
</div>
Now am getting an undefined variable $project error. So I decided to declare variable in my show() function of the CompaniesController.php like so
public function show(Company $company)
{
$company = Company::find($company->id);
$projects = Company::find(1)->projects;
return view('companies.show', ['company' => $company, 'projects' => $projects]);
}
And access variable in show.blade.php like so
<div class="jumbotron">
<h1>{{ $company->name }}</h1>
<p class="lead">{{ $company->description }}</p>
</div>
<div class="row">
#foreach($projects as $project)
<div class="col-lg-4">
<h2>{{ $project->name }}</h2>
<p class="text-danger">{{ $project->description }}</p>
<p><a class="btn btn-primary" href="/projects/{{ $project->id }}" role="button">View Projects »</a></p>
</div>
#endforeach
</div>
Now am getting a Class 'App/Project' not found error when I access show.blade.php. I am having a challenge passing company projects to the view. Any help will be appreciated. Here are my routes;
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('companies', 'CompaniesController');
Route::resource('projects', 'ProjectsController');
I would be hilarious if I am right....
In your models where defining relations replace App/Project with App\Project. Do the same for Company.... Replace "/" with "\".
You have to namespace Project class properly
Make sure file name is Project.php
Make sure inside Project.php namespace declaration is correct: namespace App;
Make sure class name inside Project.php is 'Project' : class Project extends Model { ...
Make sure you have imported it in controller. use App\Project
After all that done you will not get error:
Class 'App/Project' not found
You have correctly done passing variable in view but have a look here for another examples and methods passing about it:
https://laravel.com/docs/7.x/views
Hope this helps you
You're already using model binding. In your show method, you do not need to find. just return what you need
public function show(Company $company)
{
return view('companies.show', ['company' => $company];
}
In your view, you can then do:
#foreach($company->projects as $project)
...
#endforeach
So I cant figure out why this isnt passing the variable to my controller.
Heres my /Controllers/FriendController.php getAccept Function:
public function getAccept($username)
{
$user = User::where('username', $username)->first();
if (!$user) {
return redirect()->route('home')->with('info', 'That user could not be found!');
}
if (!Auth::user()->hasFriendRequestRecieved($user)) {
return redirect()->route('home');
}
Auth::user()->acceptFriendRequest($user);
return redirect()->route('profile.index', ['username' => $user->username])->with('info', 'Friend request acccepted.');
}
}
Heres my blade where the accept friend request button is:
#extends('templates.default')
#section('content')
<div class="row">
<div class="col-lg-5">
#include('user.partials.userblock')
<hr>
</div>
<div class="col-lg-4 col-lg-offset-3">
#if (Auth::user()->hasFriendRequestPending($user))
<p>Waiting for {{ $user->getNameOrUsername() }} to accept your request.</p>
#elseif (Auth::user()->hasFriendRequestRecieved($user))
Accept friend request
#elseif (Auth::user()->isFriendWith($user))
<p>You and {{ $user->getNameOrUsername() }} are friends.</p>
#else
Add as friend
#endif
<h4>{{ $user->getFirstNameOrUsername() }}'s friends.</h4>
#if (!$user->friends()->count())
<p>{{ $user->getFirstNameOrUsername() }} has no friends.</p>
#else
#foreach ($user->friends() as $user)
#include('user/partials/userblock')
#endforeach
#endif
</div>
</div>
#stop
Ok I fixed this myself, left out a variable in the routing so now my routing looks like this:
Route::get('friends/accept/{username}', [
'uses' => '\Aries\Http\Controllers\FriendController#getAccept',
'as' => 'friends.accept',
'middleware' => ['auth'],
]);
Forgot that:
{username}
I am a beginner in Laravel. I am trying to make a simple login form, by using a controller to manipulate the input. However everytime the code just ignore the controller function and keep calling the index everytime I submit. Please advise.
Here is the code for my form
{{ Form::open(array('action' => 'CoverController#authent')) }}
<div class="col-md-3 text-box pull-left">
{{ Form::email('email', '', array('placeholder'=>'Email')); }}
</div>
<div class="col-md-3 text-box pull-left">
{{ Form::password('password', array('placeholder'=>'Password')); }}
</div>
<div class="clearfix"> </div>
<div class="con-button">
{{ Form::submit('Sign Up / Log In'); }}
</div>
{{ Form::close() }}
Below is my routes
Route::get('/',array('as'=>'users','uses'=>'CoverController#index'));
Route::post('/','CoverController#authent');
Here is my controller function
class CoverController extends BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$view = View::make('cover');
return $view;
}
public function authent()
{
$email = Input::get('email');
$pwd = Input::get('password');
$view = View::make('formoid')->with('email',$email)->with('password',$pwd);
return $view;
}
}
With the above code,everytime the login button is pressed, the index() function is called instead of authent(), what am I doing wrong?
Try:
{{ Form::open(array('url' => '/', 'method' => 'post')) }}
Form Doc
I am attempting to create a single page like application with Laravel 4. When the user arrives at the site, they should be prompted to log in. Once the user logs in, the view (not the URL) will switch and the user will be able to see information as if they are authenticated.
My HTML (if authroized should show "Auth" in h1, if not, it shows login form)
<div class="container">
#if(Auth::check())
<h1>Auth</h1>
#else
{{ Form::open(array('url'=>'login', 'method'=>'post')) }}
<div class="row">
<div class="col-xs-12">
<div class="form-group">
{{ Form::label('email', 'Email Address') }}
{{ Form::text('email', Input::old('email'), array('class'=>'form-control', 'placeholder'=>'example#test.com')) }}
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="form-group">
{{ Form::label('password', 'Password') }}
{{ Form::password('password', array('class'=>'form-control')) }}
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
{{ Form::submit('Log In', array('class'=>'btn btn-primary pull-right')) }}
</div>
</div>
{{ Form::close() }}
#endif
</div>
Controller
class SiteController extends BaseController {
public function getIndex()
{
return View::make('index');
}
public function postLogin() {
$email = Input::get('email');
$password = Input::get('password');
if (Auth::attempt(array('email'=>$email, 'password'=>$password)))
{
return Redirect::route('index');
}
}
}
My user model is the default that ships with Laravel 4. As of now, I am passing the Auth::attempt and getting the return Redirect::route('index');, but the #if(Auth::check()) doesn't seem to be firing. Instead it continues to show me the log in form. Am I doing something wrong here?
I don't see anything wrong here, but you need to be sure what's happening, it looks like your authenticated session is not sticking, but to be sure you could:
<?php
class SiteController extends BaseController {
public function getIndex()
{
Log::info('index - authed: '. Auth::check() ? 'yes' : 'no');
return View::make('index');
}
public function postLogin() {
$email = Input::get('email');
$password = Input::get('password');
if (Auth::attempt(array('email'=>$email, 'password'=>$password)))
{
Log::info('postLogin - attempt successful');
return Redirect::route('index');
}
Log::info('postLogin - error on attempt');
}
}
And then check your logs:
php artisan tail