I'm trying to have my laravel blade to switch layouts when a checkbox is selected/unselected, no visible result so far, What I am missing? Here's the relevant part of my code.
Blade index.blade.php
...
@if ($tab == true)
<div style="background-color:green;height:100px;width:200px;">
//for test porposes a div with diff color only
some text
</div>
<input type="checkbox" name="layout" value="1" onclick="processForm()" checked>
@else
<div style="background-color:red;height:100px;width:200px;">
some text
</div>
<input type="checkbox" name="layout" value="1" onclick="processForm()">
@endif
...
@endsection
@section('scripts')
<script type="text/javascript">
function processForm() {
$.ajax( {
type: 'POST',
url: 'articles/layout',
data: { layout : $('input:checkbox:checked').val()},
success: function(data) {
$('#message').html(data);
}
} );
}
</script>
@stop
Routes
Route::resource('articles','ArticleController');
Route::post('articles/layout', [
'as' => 'articles.layout',
'uses' => 'ArticleController@layout'
]);
Finally controller ArticleController.php
<?php
namespace Vanguard\Http\Controllers\Web;
use Illuminate\Http\Request;
use Vanguard\Http\Controllers\Controller;
use Vanguard\Article;
class ArticleController extends Controller
{
public function index()
{
$articles = Article::latest()->paginate(10);
$page_title = "hello world";
$page_title_sml = "small hello world";
if (!isset($tab)) {
$tab = false;
}
return view('articles.index',compact('articles', 'page_title' , 'page_title_sml', 'tab'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
...
//custom function
public function layout(Request $request)
{
$tab = $request->layout;
return redirect()->route('articles.index')
->with('success','Layout changed');
}
//end custom function
}
My logic is: Ajax monitor checkbox > once it's checked/unchecked, Ajax send post request to articles/layout > which trigger ArticleController@layout > which process checkbox variable > redirects to Controller's articles.index > to display blade accordingly.
What I'm missing? Is there a better/simpler way to achieve this? Thanks